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";
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";
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");
}
However arrow functions are not hoisted even when declared with var
sayHi(); // sayHi is not a function
var sayHi = () => console.log("Hi");
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() {}
}
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)