This article mainly introduces the differences between function declarations and function expressions in javascript. For more information about how to declare functions in javascript, see function declaration and function expressions.
The differences are as follows:
1). For a function defined by a function declaration method, the function name is required, and the function name of the function expression is optional.
2). A function defined by a function declaration method can be called before the function declaration, while a function of a function expression can only be called after the declaration.
3 ). functions defined using function declaration methods are not real declarations. They can only appear in the global or nested in other functions, but they cannot appear in loops, condition or try/catch/finally, while
Function expressions can be declared anywhere.
The following two methods are used to define functions:
The Code is as follows:
// Function declarative
Function greeting (){
Console. log ("hello world ");
}
// Function expression
Var greeting = function (){
Console. log ("hello world ");
}
The following is an interesting javascript:
The Code is as follows:
Function f () {console. log ('I am outside! ');}
(Function (){
If (false ){
// Repeat the declare function f
Function f () {console. log ('I am inside! ');}
}
F ();
}());
What will be output? The first response should be "I am outside". The result is "I am inside" in chrome, and IE11 directly reports an error. firefox outputs "I am outside" in a lower version "...
The results output by chrome clearly reflect the features of functions declared using function declarative statements-functions can be called before they are declared.
The error reported by IE indicates that the object is missing because the function declaration is in the condition and violates the function declaration principle.
Function expression scope:
If a function declared by a function expression has a function name, the function name is equivalent to a local variable of the function and can only be called within the function. For example:
The Code 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 within the function. If it is called outside the function, an error is reported: fact is not defined.
The above is all the content of this article. I hope you will like it.