Home >Web Front-end >JS Tutorial >Function expression VS function declaration in JS, let's talk about their differences

Function expression VS function declaration in JS, let's talk about their differences

青灯夜游
青灯夜游forward
2021-07-01 10:20:452272browse

In JavaScript, function declarations and function expressions both use the function keyword to create functions. Do you think they are very similar and can be easily confused? The following article will take you to analyze function expressions and function declarations, and introduce the differences between function expressions and function declarations.

Function expression VS function declaration in JS, let's talk about their differences

In JavaScript, the function keyword can do a simple job: create a function. However, using keywords to define functions allows you to create functions with different properties.

In this article, let's take a look at how to use the function keyword to define function declarations and function expressions, and what are the differences between the two functions.

1. Function expression vs function declaration

Function declaration and function expression are 2 ways to create a function using the function keyword.

As an example to illustrate the difference, we create two versions of the sums function:

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

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

sumA(1, 2); // ???
sumB(1, 2); // ???

Try it yourself: https://jsfiddle.net/dmitri_pavlutin/8b46yokr/2/

In general, define the function as usual (sumA function). In the other case, the function is placed within a pair of parentheses (sumBfunction).

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

As expected, sumA(1, 2) returns 3. However, calling sumB(1, 2) throws an exception: Uncaught ReferenceError: sumB is not defined.

The reason for this 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 a function expression (wrap it in parentheses) which does not create a function variable in the current scope.

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

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

sum(1, 2); // => 3

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

// 函数声明:以`function`关键字开头
function sumA(a, b) {
  return a + b;
}

// 函数表达式:不以`function`关键字开头
const mySum = (function sumB(a, b) {
  return a + b;
});

// 函数表达式:不以`function`关键字开头
[1, 2, 3].reduce(function sum3(acc, number) { 
  return acc + number 
});

From a high-level perspective, function declarations are useful for creating standalone functions, but function expressions can be used as callbacks.

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

2. Function declaration

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

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

sumA(4, 5); // => 9

When a statement contains the function keyword, followed by the function name, a pair of parentheses (param1, param2, paramN) and a pair of curly braces {} Function declaration occurs when the function body in .

A function declaration creates a function variable: a variable with the same name as the function name (for example, sumA in the previous example). The function variable can be accessed in the current scope (before and after the function declaration), and even within the function scope itself.

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

For example, write a function sumArray(array) that recursively accumulates the items of an array (the array 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

Try it yourself: https://jsfiddle.net/dmitri_pavlutin/n7wcryuo/

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

Function variables containing function objects sumArrayAvailable in the current scope: sumArray([10, [1, [5]]])before and sumArray([1, [4, 6]])After the function declaration, and the scope of the function itselfsumArray([1, [4, 6]]) (recursive calls are allowed) .

Due to hoisting, function variables are available before the function is declared.

2.1 Notes on function declaration

The function declaration syntax is to create independent functions. Function declarations should be in the 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;
}

For the same reason, it is not recommended to declare conditions (if) and loops (while, for) using function declarations:

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

myFunction(2, 3);

Use function expressions for better execution of conditionally created functions.

3. Function expression

When the function keyword creates a function (with or without a name) inside an expression, The function expression will appear.

The following is an example of a function created using an expression:

// Function expressions

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
});

Two types of functions are created in a function expression:

  • If the function in the expression Without a name, like function(){return 42}, that's an anonymous function expression
  • If the function has a name, like sumB in the previous example and callback, then this is a named function expression

3.1 Notes on function expressions

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

// Functions created conditionally
let callback;
if (true) {
  callback = function() { return 42 };
} else {
  callback = function() { return 3.14 };
}

// Functions used as callbacks
[1, 2, 3].map(function increment(number) {
  return number + 1;
}); // => [2, 3, 4]

If you have created a named function expression, please note that the function variable is 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

试一试:https://jsfiddle.net/dmitri_pavlutin/sujwmp10/2/

callback是一个命名的函数表达式,因此callback函数变量仅在callback()函数使用域可用,而在外部则不可用。

但是,如果将函数对象存储到常规变量中,则可以在函数作用域内外从该变量访问函数对象:

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

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

试一试:https://jsfiddle.net/dmitri_pavlutin/1btmrcu2/1/

4. 总结

根据使用function关键字创建函数的方式,可以通过两种方法来创建函数:函数声明和函数表达式。

留个问题: function sum(a, b) { return a + b } + 1 是函数声明还是函数表达式,可以在留言中说出你的答案。

英文文章地址:https://dmitripavlutin.com/javascript-function-expressions-and-declarations/

作者:Dmitri Pavlutin

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Function expression VS function declaration in JS, let's talk about their differences. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete