There are two ways to declare functions in javascript: function declarative and function expression.
The differences are as follows:
1). For functions defined by methods declared by function, the function name is necessary, while the function name of the function expression is optional.
2). Functions defined by methods declared by function can be called before function declaration, while functions of function expressions can only be called after declaration.
3). Functions defined by methods declared by function are not real declarations. They can only appear globally or nested in other functions, but they cannot appear in loops, conditions, or try/catch/finally, and
Function expressions can be declared anywhere.
The following are two methods to define the function:
The code copy is as follows:
// Function declarative formula
function greeting(){
console.log("hello world");
}
//Function expression
var greeting = function(){
console.log("hello world");
}
Here is an interesting javascript:
The code copy is as follows:
function f() { console.log('I am outside!'); }
(function () {
if(false) {
// Repeat the function f
function f() { console.log('I am inside!'); }
}
f();
}());
What will output? The first reaction should be "I am outside". As a result, "I am inside" is output in chrome, IE11 directly reported an error, and the lower version of firefox outputs "I am outside"...
The result of chrome output clearly reflects the characteristics of functions declared with function declarative expressions - functions can be called before declaration.
IE error shows that the object is missing because the function declaration is in the condition, which violates the principle of function declaration.
Scope of function expressions:
If the function declared by the function expression has a function name, then the function name is equivalent to a local variable of the function and can only be called inside the function. For example, a chestnut:
The code copy is as follows:
var f = function fact(x) {
if (x <= 1)
return 1;
else
return x*fact(x-1);
};
alert(fact()); // Uncaught ReferenceError: fact is not defined
fact() can be called inside the function, but an error will be reported when called outside the function: fact is not defined
The above is all about this article, I hope you like it.