While coding I realized that certain variable names such as top
, self
, left\right
create all sorts of errors when you try to use them. What's the reason behind this in JavaScript, while other languages can use them?
Why can't I use certain variable names in javascript?
532 views Asked by Ali Camilletti AtThere are 3 answers
There are no problems using variables with those names in JavaScript in most cases.
In some environments, some of the names are already used for existing global variables and are read only.
top
is one such example, it refers to the top level frame.
You can still use it as the name of a variable in a non-global context.
Most probably you use variables without declaring them with var
/let
, and in such circumstances, you modify properties of the global execution environment.
In browser, the global execution environment is window
, so when you do
self = '...'
you effectively do
window.self = '...'
self
, top
, left
, right
are properties of window
object which may have certain non-standard behaviors. Many built-in properties of window
object are in fact implicit setters which do more than setting a variable - they can also modify the current page, navigate etc. Also, many built-in properties of window
can not be overridden, so assigning to them has no effect.
Contrary, when you do
(function() {
var self = '...'
})()
you should not have any problems.
You need a function call to make it work properly, to create a new scope, because in global scope, even with var
, you'd still implicitly assign a property to window
.
You can't use them as global variables because there already exist global accessor properties with these names.
top
is used to access the top frame.self
is used to access the global object.left
andright
.Attempting to assign some value to these variables will run the setter, which may not do what you expected. If there is only a getter but no setter, the assignment will be ignored in sloppy mode and throw in strict mode.
There is no problem in using these names as local variables. You should not use global variables anyways.