Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const vs var and the window.name property [duplicate]

Just came across the following in a recent question I was looking at, and I'm curious as to why var name and const name offer varying outputs. Run the snippets below to see what I mean.

If it has anything to do with name being a window object property, then re-declaring/defining name with const should result in an error I would think. However, in the example(s) below, const allows for the re-declaration of name as an array, while var does not.

var name = ['one', 'two', 'three', 'four', 'five'];
for (var i=0; i < name.length; i++){
    document.write(name[i] + '<br>');
}

const name = ['one', 'two', 'three', 'four', 'five'];
for (var i=0; i < name.length; i++){
    document.write(name[i] + '<br>');
}

So, why does const allow me to hijack the window.name property and reassign it as an array? But var does not allow for the reassignment (remains as default string)? Or am I simply looking at it the wrong way?

like image 268
mferly Avatar asked Jan 06 '23 23:01

mferly


1 Answers

Because const, like let, is lexically scoped, and the top-level lexical scope is not the same as global scope. Here's an analogy:

function f(){
  var name = 1;
  {
    var name = 2; // does not create a new variable, because name already exists at the top level of the function
  }
  console.log(name); // 2
}

function g(){
  var name = 1;
  {
    const name = 2; // creates a new variable
  }
  console.log(name); // 1
}

const isn't hijacking window.name; it's just shadowing it. You can see this by observing in your second case that window.name remains unchanged. You can think of top-level code as if it's within the nested block in the functions above: var declarations get put in the global scope, but let and const declarations do not.

like image 87
Bakkot Avatar answered Jan 08 '23 15:01

Bakkot