DEV Community

Cover image for Understanding hoisting in JavaScript
Shakhor Smith
Shakhor Smith

Posted on

4 1

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 😄.
You can find me on Twitter/IG: @smithmanny

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more