3 types of functions in JavaScript — Expressions, Declarations and Arrows
2 min readFeb 10, 2021
the case
Currently there are three ways of creating functions in JavaScript
- function declaration
- function expression
- new arrow function
1. pre-2015
1.1. function declaration
- function keyword
- function name
- parameters within parenthesis
- code block within curly brackets
1.2. function expression
- var initialization (const in ecma 2015)
- function keyword
- parameters within parenthesis
- code block within curly brackets
2. difference between function expressions and function declarations
- function expressions are part of the regular top-to-down flow of control
- function declaration are exempt from this and moved immediately to the top of the script and initialized immidiately
- in other words, function declarations are hoisted but function expressions are not
3. enter arrow function
- variable declaration
- parameters in parenthesis
- arrow made from => (equal + gt)
- code block within curly brackets
- if you have just a single argument, you don’t need
()
- but without or with multiple, you need
()
3.1. minified arrow functions
- if you are only using a single line of code, you don’t need return
- if you have a single line of code, you don’t need curly brackets
- no parents with single arguments
- no curly brackets with a single line of code
- no return keyword with a single line of code
Originally published at http://pavol.kutaj.com on February 10, 2021.