A function is a block of code, self contained, that can be defined once and run any times you want.

A function can optionally accept parameters, and returns one value.

Functions in JavaScript are objects. Their superpower lies in the fact that they can be invoked.

Functions in JavaScript are called first class functions because they can be assigned to a value, and they can be passed as arguments and used as a return value.

Syntax for functions

Let’s start with the “old”, pre-ES6/2015 syntax. Here’s a function declaration:

function doSomething(foo) {
  // do something

(now, in post ES6/ES2015 world, referred as a regular function)

Functions can be assigned to variables (this is called a function expression):

const doSomething = function(foo) {
  // do something

Named function expressions are similar, but play nicer with the stack call trace, which is useful when an error occurs - it holds the name of the function:

const doSomething = function doSomething(foo) {
  // do something

ES6/ES2015 introduced arrow functions, which are especially nice to use when working with inline functions, as parameters or callbacks:

const doSomething = foo => {
  //do something

Arrow functions have an important difference from the other function definitions above, we’ll see which one in the next lesson.

Go to the next lesson