抹桥的博客
Language
Home
Archive
About
GitHub
Language
主题色
250
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 function

The 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.

This article was published on February 9, 2015 and last updated on February 9, 2015, 3892 days ago. The content may be outdated.

The Difference Between JavaScript Function Expressions and Function Declarations
https://blog.kisnows.com/en-US/2015/02/09/jsfunction-expression-declaration/
Author
Kisnows
Published at
2015-02-09
License
CC BY-NC-ND 4.0