Understanding hoisting in JavaScript

One problem new JavaScript developers face is understanding that variables and functions are “hoisted”. While some developers intend for hoisting to happen, others are faced with unexpected results and don’t understand why.

First, what is hoisting?

// Outputs: undefined
console.log(car);
var car = 'Audi';

Hoisting by definition is to “raise or lift” and that’s exactly what JavaScript does when it runs our code. For example, JavaScript would have read our code snippet above as:

var car;

// Outputs: undefined
console.log(car);

// JavaScript sets our car variable afterwards
car = 'Audi';

As you can see our variable car is declared at the top of our file with a value set to “undefined”. Then once JavaScript gets to our variable it will reassign that variable to what we passed it.

You might be asking yourself, what about functions? Functions are hoisted as well, but with a catch. Unlike variables, functions actually hoist the whole function definition, but only if it’s a function declaration. For function expressions, the variable itself is hoisted, but the actual function definition is not.

// Outputs: 'slyderz.co'
someFunc() 

function someFunc() {
    return 'slyderz.co'
}


// Outputs: site is undefined
site();

var site = function someFunc() {
    return 'slyderz.co'
}

That's all for now 😄.