Is Function Declaration Hoisted in JavaScript?

In JavaScript, before the code is executed, the interpreter moves/hoists function declarations/statements to the top of their scope (which is either an enclosing function or the global scope). This means that you can call the function before it is declared. For example:

hoisted(); // 'foo'

function hoisted() {
    console.log('foo');
}

This can lead to confusion, erroneous code and sometimes unexpected results:

function hoisted() {
    console.log('foo');
}

hoisted(); // 'bar'

function hoisted() {
    console.log('bar');
}

To prevent functions from being used before they are declared, you can instead use function expressions.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.