Hoist

Hoist in JavaScript

Was reading Airbnb style guide for React and get confused when it says

relying on function name inference is discouraged

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// bad
class Listing extends React.Component {
render() {
return <div>{this.props.hello}</div>;
}
}
// bad (relying on function name inference is discouraged)
const Listing = ({ hello }) => (
<div>{hello}</div>
);
// good
function Listing({ hello }) {
return <div>{hello}</div>;
}

Then Googled and found someone mentioned Hoisting in JS.
Just want to write down somthing of what I have learnt from the reading.

So basicly, JS can look ahead of code and find all variable declarations and hosit them to the top of the function.
For example:

1
2
3
4
5
6
7
// Outputs: undefined
console.log(declaredLater);
var declaredLater = "Now it's defined!";
// Outputs: "Now it's defined!"
console.log(declaredLater);

The first log didn’t throw an error saying declaredLater is not defined, instead, it prints undefined.
This is because of variable hoisting, the above code is actually equivalent to:

1
2
3
4
5
6
7
8
9
var declaredLater;
// Outputs: undefined
console.log(declaredLater);
declaredLater = "Now it's defined!";
// Outputs: "Now it's defined!"
console.log(declaredLater);

For function, hoisting works differently, I’m using some quote cuz i’m lazy :p

However, function definition hoisting only occurs for function declarations, not function expressions. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
// Outputs: "Definition hoisted!"
definitionHoisted();
// TypeError: undefined is not a function
definitionNotHoisted();
function definitionHoisted() {
console.log("Definition hoisted!");
}
var definitionNotHoisted = function () {
console.log("Definition not hoisted!");
};

Finally, one thing to add-on.

Function’s name doesn’t get hoisted if it is part of a function expression.

1
2
3
4
5
6
7
8
9
// ReferenceError: funcName is not defined
funcName();
// TypeError: undefined is not a function
varName();
var varName = function funcName() {
console.log("Definition not hoisted!");
};

Reference: Variable and Function Hoisting in JavaScript