What is Function Hoisting in JS?

Hi all. I already learned how to define and use a function, like this:

function printEachChar(str) {
    for (let letter of str) {
        console.log(letter);
    }
}
printEachChar("Hello World");

But what if I use a function, like this?

calculateSum(4, 6);
function calculateSum(a, b) {
    console.log(a + b);
}

What is Function Hoisting in JS? And what does it means?? :confused:

If you guys know, then explain about function hoisting in JavaScript. :grinning:

Thank you!
Pummarin :smile:

You will find it Here in details

Essentially, hoisting is the way variables declared with var and function declarations, just like the one in your example, are pushed to the top of the code. JavaScript reads from top to bottom;but In that way, those declarations can be used before the are declared. That is, you could call a function in line 8 and declared it in line 50.

It’s not the same with variables declared with let, const (const), function expression (class expression included). You have to declare them before using them, otherwise, you get an error.

I would argue the second approach is better for readability. For example,

const myFuc = function()  {
return {name: 'sam'}
}

myFuc() // must be called after the func expression has been declared (const was even used anyways)
myFuc() // works because myFuc was hoisted

function myFuc() {
return {name: 'sam'}

}

1 Like