Here is an example of a function declaration: In the first example, the function is declared with the function keyword. The function name is myFunction.
function myFunction() {
console.log("Hello!");
}
Declarations are loaded before any code can run. Function declarations load before any code is executed while Function expressions load only when the interpreter reaches that line of code. Similar to the var statement, function declarations are hoisted to the top of other code.
Here is an example of a function expression: In the second example, the function is created with the function keyword, but the function name is omitted. The function is assigned to the variable myFunction.
const myFunction = function() {
console.log("Hello!");
};
We often see anonymous functions used with ES6 syntax like so:
Arrow function expressions
const myFunction = () => {}
Here is an example of an IIFE: In this example, the function is created and invoked immediately. The function is not assigned to a variable.
(function() {
console.log("Hello!");
})();
IIFE
The name — immediately invoked function expressions — pretty much says it all here. When a function is created at the same time it is called, you can use an IIFE, which looks like this:
(function() => {})()
or:
(() => {})()
In general, you should use function declarations when you want to create a function that is accessible from anywhere in your code. You should use function expressions when you want to create a function that is only accessible within a specific scope.
Use a function declaration when:
you need a more readable and understandable function (such as a long function, or one you’ll need to use in different places)
an anonymous function won’t suit your needs
you need to create a function that is recursive
you need to call the function before it is defined
Use a function expression when:
you need a more flexible function
you need a function that isn’t hoisted
the function should only used when it is defined
the function is anonymous, or doesn’t need a name for later use
you want to control when the function is executed, using techniques like immediately-invoked function expressions (IIFE)
you want to pass the function as an argument to another function
1. Expressed functions cannot be used before initialization
Hoisting
Hoisting refers to the availability of functions and variables “at the top” of your code, as opposed to only after they are created. The objects are initialized at compile time and available anywhere in your file.
Function declarations are hoisted but function expressions are not.
It’s easy to understand with an example:
doStuff();
function doStuff() {};
The above does not throw an error, but this would:
doStuff();
const doStuff = () => {};
解析器会率先读取函数声明(声明提升),并使其在执行任何代码之前可用
alert(sum(10,10));
function sum(num1,num2){
return num1+num2;
}
函数表达式必须等到解析器执行到它所在的代码行,才会真正被解析执行
alert(sum(10,10)); //报错
var sum = function(num1,num2){
return num1+num2;
}
Named function expression
If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This avoids using the deprecated arguments.callee property to call the function recursively.
const math = {
factit: function factorial(n) {
console.log(n);
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
},
};
math.factit(3); //3;2;1;
Unlike declarations, the name of the function expressions is read-only.
function foo() {
foo = 1;
}
foo();
console.log(foo); // 1
(function foo() {
foo = 1; // TypeError: Assignment to constant variable.
})();
3. Anonymous functions are useful for anonymous operations
There are cases where you do not need to use a function later. You can execute the function instantly. In such cases, you do not need a name, so you can use a function expression instead of a declaration.
Callbacks
A function passed to another function is often referred to as a “callback” in JavaScript. Here’s an example:
function mapAction(item) {
// do stuff to an item
}
array.map(mapAction)
array.map(mapAction)
The problem here is that mapAction will be available to your entire application — there’s no need for that. If that callback is a function expression, it will not be available outside of the function that uses it:
array.map(item=>{//do stuff to an item })
or
const mapAction=function(item){// do stuff to an item}
array.map(mapAction)
though mapAction will be available to code below its initialization.
Using a function as a callback
More commonly it is used as a callback:
button.addEventListener("click", function(event){console.log("button is clicked!");});
Using a function declaration here will not throw an error, but the name of the function will be inaccessible:
(function print(){console.log('deeecode')})() // deeecode
print() // ReferenceError: print is not defined
Using a function declaration, the IIFE is executed, but you cannot access the name of the function outside the parenthesis.