Hoisting inside function having same variable name

You would be right if the var was called b, but the var a already exists. redeclaring a javascript variable that already exists doesn't do anything. It will not change the value to undefined. Try it.

function hoist(a) {
    var a; // no op, does not change a to  undefined.
    console.log(a);
    a = 10;
}

hoist(18);


This falls back in the section Only declarations are hoisted in the MDN (to link some documentation, at least).

The second example given there is the exact one you're looking for:

num = 6;
console.log(num); // returns 6
var num; // or, really, var num = whatever.

To just recall what is said:

If you declare the variable after it is used, but initialize it beforehand, it will return the value.

Tags:

Javascript