Is Function Declaration Hoisted in JavaScript?

Find out if JavaScript function declaration/statement is hoisted or not

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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.