178 words
1 minutes
The Difference Between JavaScript Function Expressions and Function Declarations
Two Ways to Define Functions in JavaScript:
Function Expression:
var foo = function(){
conlose.log('Message');
};Function Declaration:
function foo(){
console.log('Message');
};Both methods can define the same function, but there are some differences:
In Function Expressions:
var foo, like any variable defined with var, is hoisted to the top of the function or script scope, but the function body remains in its original place. Therefore, the function must be called after its definition.
var foo = function(){
console.log('Message');
};
foo() // Outputs 'Message'
foo();
var foo = function(){
console.log('Message');
}; // This will throw a TypeError: Property 'test' of object #<Object> is not a functionThe second code snippet above is actually equivalent to the following, which is why it throws an error:
var foo;
foo();
var foo = function(){
console.log('Message');
};In Function Declarations:
The entire function block of the foo() function is hoisted to the top of the entire function or script scope, making it visible throughout. This means you can call the function before its definition.
foo()
function foo(){
console.log('Message')
} // Outputs 'Message'In practical use, it’s important to pay close attention to the differences between the two.
The Difference Between JavaScript Function Expressions and Function Declarations
https://blog.kisnows.com/en-US/2015/02/09/jsfunction-expression-declaration/