There are two ways to declare a function in JavaScript: function declaration and function expression.
The difference is as follows:
1). A function that is defined by a method declared by a function, the function name is required, and the function name of the function expression is optional.
2). A function that is defined in a method declared by a function can be called before a function declaration, whereas a function of a function expression can only be called after a declaration.
3). Functions defined as function declarations are not true declarations, they can only appear in the global, or nested in other functions, but they cannot appear in loops, conditions, or try/catch/finally, and
function expressions can be declared anywhere.
The functions are defined in two different ways:
1 // function greeting () { 3 console.log ("Hello World" ); 4 " 6 // function expression var greeting = function { 9 Console.log (" Hello World "); 10 }
Here's an interesting javascript:
1 function f () {Console.log (' I am outside! ' ); }2 (function () {3 if(false) {4 /// repeat functionf5functions F () {Console.log (' I am inside! ') ); }6 }7 f (); 8 } ());
What will it output? The first reaction should be "I am outside" bar. Results in chrome output "I am inside", IE11 direct error, Firefox lower version output "I am outside" ...
The result of chrome output is a clear response to the feature of functions declared with function declarations--functions that can be called before they are declared.
IE error display missing object, because function declaration in the condition, violate the principle of function declaration.
Scope of the function expression:
If a function expression declares a function with a function name, then the function name is equivalent to a local variable of the function, which can only be called inside the function, for example, a chestnut:
1 varf =functionFact (x) {2 if(x <= 1) 3 return1;4 Else 5 returnX*fact (x-1);6 };7Alert (fact ());//uncaught referenceerror:fact is not defined
Fact () can be called inside a function, and an error is called outside the function: fact is undefined.
Fact
The difference between a JavaScript function declaration and a function expression (learning notes)