Today I ran into an issue that top
is a pre-existing global variable.
const left = 1;
const right = 2;
const top = 3;
const bottom = 4;
console.log(left, right, top, bottom);
result:
Uncaught SyntaxError: Identifier 'top' has already been declared
I think I've just been lucky until today that most of the time my usage of a variable called top
was inside a function.
How much do I need to worry about browsers adding new global variables that will break code in the future? It seems like until es6 import pretty much all browser libraries used global variables unless they had a build step. But, looking at the top
example it seems like browser could add new unsettable global variables at anytime and therefore they should be avoided at all costs. I see some variables things like HTMLElement
are assignable.
console.log(HTMLElement);
HTMLElement = 'foo';
console.log(HTMLElement);
result:
function HTMLElement() { [native code] }
foo
Is top
some legacy thing but browser specs promise not to do more of that in the future? Like I can't assign window
const window = 'foo';
console.log(window);
result:
SyntaxError: Identifier 'window' has already been declared
but I can assign process
in node
Welcome to Node.js v12.6.0.
Type ".help" for more information.
> process
process {
version: 'v12.6.0',
versions: {
node: '12.6.0',
...
}
> process = 'foo'
'foo'
> process
'foo'
>
console.log(Object.entries(Object.getOwnPropertyDescriptors(window)).filter(d => !d[1].configurable).map(d => d[0]))
gives me this quite short list, considering the number of properties in the global object:["document", "NaN", "window", "Infinity", "undefined", "location", "top"]
. Those are the property names that, used withconst
, will throw the error you described. – Agricultureclosed
being logged asfalse
, if I define it globally as0
?. In this answer, there’s a larger list of such non-configurable, non-writable, or setter properties. There’s a difference between usingvar
vs.let
orconst
in global scope — if assignment doesn’t throw an error,const
orlet
actually creates the variable with the new value, as opposed tovar
. However, properties liketop
,window
ordocument
throw an error when assigning to them, but why those and not e.g.closed
orhistory
? – Stupefacient