24 lines
846 B
Plaintext
24 lines
846 B
Plaintext
---
|
|
title: Explain the differences on the usage of `foo` between `function foo() {}` and `var foo = function() {}`
|
|
---
|
|
|
|
The former is a function declaration while the latter is a function expression. The key difference is that function declarations have its body hoisted but the bodies of function expressions are not (they have the same hoisting behavior as variables). For more explanation on hoisting, refer to the question on [hoisting](/questions/quiz/explain-hoisting). If you try to invoke a function expression before it is defined, you will get an `Uncaught TypeError: XXX is not a function` error.
|
|
|
|
## Function Declaration
|
|
|
|
```js
|
|
foo(); // 'FOOOOO'
|
|
function foo() {
|
|
console.log('FOOOOO');
|
|
}
|
|
```
|
|
|
|
## Function Expression
|
|
|
|
```js
|
|
foo(); // Uncaught TypeError: foo is not a function
|
|
var foo = function () {
|
|
console.log('FOOOOO');
|
|
};
|
|
```
|