Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom.
In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.
In JavaScript, the function keyword does a simple job: create a function. However, you can create functions with different attributes by defining functions using keywords.
In this article, we’ll look at how the function keyword is used to define function declarations and function expressions, and what the differences are between the two.
Function expressions vs function declarations
Function declarations and function expressions are two ways to create functions using the function keyword.
To illustrate the discrepancy, 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); // ???
Copy the code
Try it: jsfiddle.net/dmitri_pavl…
In general, define the function (sumA function) as usual. In the other case, the function is placed in a pair of parentheses (sumB function).
What happens if you call sumA(1,2) and sumB(1,2)?
As expected, sumA(1, 2) returns 3. However, calling sumB(1, 2) raises 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 (wrapped in parentheses) that 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); / / = > 3Copy the code
If the statement begins with the keyword 'function', it is a function declaration; otherwise, it is a function expression.Copy the code
Function sumA(a, b) {return a + b; Const mySum = (function sumB(a, b) {return a + b; }); // Function expressions: do not start with '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 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 saw in the previous example, sumA is a function declaration:
// Function declaration function sumA(a, b) { return a + b; } sumA(4, 5); / / = > 9Copy 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 body of the function enclosed in a pair of curly braces {}.
The 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 is accessible 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 (to higher-order functions).
For example, write a function sumArray(array) to recursively sum the items of 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]]); / / = > 11Copy the code
Try it: jsfiddle.net/dmitri_pavl…
function sumArray(array) { … } is a function declaration.
The function variable sumArray containing the function object is available in the current scope: SumArray ([10, [1, [5]]) before and after sumArray([1, [4, 6]])), and the scope of the function itself sumArray([1, [4, 6]]) (allowing recursive calls).
Function variables are available before function declarations due to promotion.
2.1 Precautions for function declaration
The function declaration syntax is used to create standalone 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 conditions (if) and loops (while, for) :
// Bad!
if (myCondition) {
function myFunction(a, b) {
return a * b;
}
} else {
function myFunction(a, b) {
return a + b;
}
}
myFunction(2, 3);
Copy the code
Use function expressions to better perform conditionally created functions.
3. Function expressions
The function expression appears when the function keyword creates a function (with or without a name) inside the expression.
Here 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 });Copy the code
Two kinds of functions are created in function expressions:
- If the function in the expression does not have a name, for example
Function () {return 42}
That is an anonymous function expression - If the function has a name, as in the previous example
sumB
And the callback, so this is a named function expression
3.1 Considerations of 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]Copy the code
If you have created a named function expression, note that the function variable is only available in 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 definedCopy the code
Give it a try: jsfiddle.net/dmitri_pavl…
Callback is a named function expression, so the callback function variable is only available in the callback() field, not outside.
However, if you store a function object in a regular variable, 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
Give it a try: jsfiddle.net/dmitri_pavl…
4. To summarize
Depending on how functions are created using the function keyword, there are two ways to create functions: function declarations and function expressions.
Function sum(a, b) {return a + b} + 1 function sum(a, b) {return a + b} + 1
The possible bugs in editing can not be known in real time. In order to solve these bugs after the event, I spent a lot of time on log debugging. By the way, I recommend a good bug monitoring tool for youFundebug.
By Dmitri Pavlutin
Original text: dmitripavlutin.com/javascript-…
communication
This article is updated weekly, you can search wechat ** [big move the world] the first time to read, reply [welfare] ** there are many front-end video waiting for you, this article GitHub github.com/qq449245884… Already included, welcome Star.