Why can't I use certain variable names in javascript?

532 views Asked by At

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?

3

There are 3 answers

0
Oriol On BEST ANSWER

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.
  • As far as I know there is no problem with left and right.

console.log(Object.getOwnPropertyDescriptor(window, 'top'));
console.log(Object.getOwnPropertyDescriptor(window, 'self'));

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.

(function() {
  var top = 123; // local variable
  console.log(top === 123); // true - no problem
})();
var top = 456; // global variable
console.log(top === 456); // false !!!

0
Quentin On

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.

2
jakub.g On

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.