DEV Community

Cover image for Hoisting in Javascript
hacker4world
hacker4world

Posted on

Hoisting in Javascript

In javascript, hoisted objects are objects that can be accessed before their declaration in the code without javascript throwing an error complaining about it.
some things can be hoisted like variables, functions and classes

Variables declared with var

if we try to access a variable declared with var before it's declaration in the code it's value will be undefined

console.log(name); //undefined
var name = "John";
Enter fullscreen mode Exit fullscreen mode

again javascript will set that variable to undefined instead of throwing an error

Variables declared with let and const

these variables are not hoisted and will cause an error if accessed before declaration

console.log(name); //reference error: name is not defined
const name = "John";
Enter fullscreen mode Exit fullscreen mode

Functions

functions are also hoisted and their value will be the function itself which means it can be used perfectly before declaration

sayHi(); //Hi
function sayHi() {
   console.log("Hi");
}
Enter fullscreen mode Exit fullscreen mode

However arrow functions are not hoisted even when declared with var

sayHi(); // sayHi is not a function
var sayHi = () => console.log("Hi");
Enter fullscreen mode Exit fullscreen mode

ES6 Classes

classes are not hoisted and will cause an error when accessed before declared

const person = new Person(); //cannot access 'Person' before initialization

class Person {
  constructor() {}
}
Enter fullscreen mode Exit fullscreen mode

Summary

var variables: hoisted and undefined by default
const variables: not hoisted
functions: hoisted and can be used
arrow functions: not hoisted
classes: not hoisted

Top comments (0)