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?