3 types of functions in JavaScript — Expressions, Declarations and Arrows

Pavol Kutaj
2 min readFeb 10, 2021

--

the case

Currently there are three ways of creating functions in JavaScript

  1. function declaration
  2. function expression
  3. new arrow function

1. pre-2015

1.1. function declaration

  1. function keyword
  2. function name
  3. parameters within parenthesis
  4. code block within curly brackets

1.2. function expression

  1. var initialization (const in ecma 2015)
  2. function keyword
  3. parameters within parenthesis
  4. 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

  1. variable declaration
  2. parameters in parenthesis
  3. arrow made from => (equal + gt)
  4. 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
  1. no parents with single arguments
  2. no curly brackets with a single line of code
  3. no return keyword with a single line of code

Originally published at http://pavol.kutaj.com on February 10, 2021.

--

--

No responses yet