TIL function hoisting in JS
POSTED ON:
TAGS: javascript
We know hoisting creates unintended side effect within JS.
It's why we switch from var to let & const.
There's also side efects with functions.
Via Type of NaN - A quiz system to test your JS
Consider the following declarations and expression. What gets logged?
Example 1: #
immaBeOnTop();
var immaBeOnTop;
function immaBeOnTop() {
console.log('first');
}
immaBeOnTop = function() {
console.log('second');
};
result:
first
- The
varis hoisted. - The
function immaBEOnTop()is hoisted. - Then we start going down the list of commands.
- We then run the
immaBeOnTop();
Example 2: #
spitNumbers();
function spitNumbers() {
console.log("first");
}
var spitNumbers = function() {
console.log("second");
};
function spitNumbers() {
console.log("third");
}
spitNumbers();
result:
third
second
- the
firstgets hoisted. - The
thirdgets hoisted, and overrides. spitNumbers();is called, and returnsthird.- We then move down to the next function,
var spitNumbers = function(). That overrides the result. spitNumbers();is called again, and returnssecond.
Related TILs
Tagged: javascript