Search code examples
javascriptfunctionscopevarhoisting

If a var in JavaScript is defined twice, which definition should the interpreter take?


I'm new to JavaScript and am trying to understand the concepts of hoisting and scope.

Case 1

var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);

and I have the following output in the console

Auro 1
Auro 2

If I understand hoisting correctly, JS engine hoists the declaration of a variable first and then automatically assigns a value undefined to it. Only when it encounters the assignment (=) operator, does it actually assign the intended value to it.

If my understanding above is correct, then the first time the logName function was called, the variable name should have printed undefined, but it is printing the value.

Case 2

var name;

function logName(num) {
  console.log(name, num);
}

logName(1);
name = "Auro";
logName(2);
name = "Baner";

Output in the console:

Baner 1
Auro 2

This confuses me even more. Here the first call to the function logName picked the later assignment to the variable and printed Baner, however, the second call picked the previous assignment, that is Auro.

What is going on here? What am I missing?


Solution

  • In the global scope, name refers to window.name, that is the name property of the window - which in the examples you gave are sif1 and sif2 (possibly "Snippet IFrame 1/2").

    Since window.name already exists, var name; in the global scope does nothing. The variable is already defined.

    Until you overwrite it - and note that again you are setting the global window.name property. And, depending on browser settings, this can persist across reloads of the page (since you're naming the entire window). This explains why you see the value "stick".