In JavaScript, the function keyword does a simple job: it creates a function. However, you can create functions with different attributes by defining functions using keywords.

In this article, you’ll learn how to use the function keyword to write function declarations and function expressions, and what the differences are between the two types of functions.


Function expressions VS function declarations

Function declarations and Function expressions are two ways to create functions using the Function keyword.

To illustrate the difference, let’s create two versions of the summation function:

function sumA(a, b) {
  return a + b;
}

(function sumB(a, b) {
  return a + b;
});

sumA(1.2); // ???
sumB(1.2); // ???
Copy the code

In one case, functions can be defined as usual (e.g. SumA ()). In another case, the function is placed within a pair of parentheses (e.g. SumB ()).

What happens if you call sumA(1,2) and sumB(1,2)?

As expected, sumA(1, 2) simply returns the sum of 1 and 2 numbers. However, calling sumB(1, 2) throws an uncaught ReferenceError: sumB is not defined.

The reason is that sumA is created using a function declaration that creates a function variable (with the same name as the function name) in the current scope. But sumB is created using function expressions (which are enclosed in parentheses), and it does not create function variables in the current scope.

If you want to access a function created using a function expression, save the function object in a variable:

// Works!
const sum = (function sumB(a, b) {
  return a + b;
});

sum(1.2); / / = > 3
Copy the code

Here’s a quick reminder of how to distinguish a function declaration from a function expression:

If the statement begins with the function keyword, it is a function declaration; otherwise, it is a function expression.

// Function declaration: starts with the 'function' keyword
function sumA(a, b) {
  return a + b;
}

// Function expressions do not start with the 'function' keyword
const mySum = (function sumB(a, b) {
  return a + b;
});

// Function expressions do not start with the 'function' keyword
[1.2.3].reduce(function sum3(acc, number) { 
  return acc + number 
});
Copy the code

At a higher level, function declarations are useful for creating stand-alone functions, but function expressions are great as callbacks.

Now let’s take a closer look at the behavior of function declarations and function expressions.

2. Function declaration

As you’ve seen in the previous example, sumA is a function declaration:

// Function declaration
function sumA(a, b) {
  return a + b;
}

sumA(4.5); / / = > 9
Copy the code

Function declarations occur when a statement contains the function keyword, followed by the function name, a pair of parentheses with arguments (param1, param2, paramN), and the function body enclosed in a pair of ** braces {}**.

The function declaration creates a function variable — ** a variable with the same name as the function (** such as sumA in the previous example). Function variables can be accessed in the current scope (before and after the function declaration), or even within the function scope itself.

Function variables are usually used to call functions or pass function objects to other functions (higher-order functions).

For example, we write a function sumArray(array) that recursively sums the items in an array (which can contain numbers or other arrays) :

sumArray([10[1[5]]]); / / = > 16

function sumArray(array) {
  let sum = 0;
  for (const item of array) {
    sum += Array.isArray(item) ? sumArray(item) : item;
  }
  return sum;
}

sumArray([1[4.6]]); / / = > 11
Copy the code

Function sumArray (array) {… } is a function declaration.

Function variables sumArray that contain function objects are available in the current scope: function declarations before and after sumArray([10, [1, [5]]]), and sumArray(item) within the scope of the function itself (allowing recursive calls).

Function variables are available before function declarations due to variable promotion.

2.1 Precautions for function declaration

The function declaration syntax is used to create separate functions. Function declarations should be in global scope or directly in the scope of other functions:

// Good!
function myFunc1(param1, param2) {
  return param1 + param2;
}

function bigFunction(param) {
  // Good!
  function myFunc2(param1, param2) {
    return param1 + param2;
  }

  const result = myFunc2(1.3);
  return result + param;
}
Copy the code

For the same reason, it is not recommended to use function declarations in conditional statements (if) and loop statements (while, for) :

// Bad!
if (myCondition) {
  function myFunction(a, b) {
    returna * b; }}else {
  function myFunction(a, b) {
    return a + b;
  }
}

myFunction(2.3);
Copy the code

Using function expressions makes it easier to create functions in conditional statements.

3. Function expressions

The function keyword is a function expression when it creates a function (with or without a name) in an expression.

Here is an example of a function created using an expression:

// Function expression

const sum = (function sumB(a, b) {
  return a + b;
});

const myObject = {
  myMethod: function() {
    return 42; }};const numbers = [4.1.6];
numbers.forEach(function callback(number) {
  console.log(number);
  // logs 4
  // logs 1
  // logs 1
});
Copy the code

There are two types of functions created in function expressions:

  1. ifThe function inside the expression has no name, e.g.function() {return 42}, then this is aAnonymous function expression;
  2. ifFunctions have names, as in the previous examplesumBandcallbackSo this is oneNamed function expression.

3.1 Considerations of function expressions

Function expressions are suitable for callbacks or functions created by conditions:

// The function created by the condition
let callback;
if (true) {
  callback = function() { return 42 };
} else {
  callback = function() { return 3.14 };
}

// as a callback function
[1.2.3].map(function increment(number) {
  return number + 1;
}); // => [2, 3, 4]
Copy the code

If you have created a named function expression, note that function variables are only available within the scope of the created function:

const numbers = [4];
numbers.forEach(function callback(number) {
  console.log(callback); // logs function() { ... }
});

console.log(callback); // ReferenceError: callback is not defined
Copy the code
  • CallbackIs a named function expression, thereforeCallbackFunction variables can only be inCallback()Function scope, not inCallback()Used outside the scope of a function.

However, if you store the function object in a regular variable, then you can access the function object from that variable inside and outside the function scope:

const callback = function(number) {
  console.log(callback); // logs function() { ... }
};

const numbers = [4];
numbers.forEach(callback);
console.log(callback); // logs function() { ... }
Copy the code

4. To summarize

Depending on how functions are created using the function keyword, functions can be created in two ways: function declarations and function expressions.

Function declarations occur in statements starting with the function keyword:

// Function declaration
function sumA(a, b) {
  return a + b;
}
Copy the code

Function declarations are useful for creating independent, generic functions.

However, if a statement does not begin with the function keyword, then there is a function expression:

// Function expression
(function sumB(a, b) {
  return a + b;
});
Copy the code

Functions created using function expressions are useful for creating callback functions or functions based on conditions.

Finally, to everyone:

function sum(a, b) { return a + b } + 1;
Copy the code

Function declaration or function expression, leave your answer in the comments!