Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript identifiers not to use

Tags:

javascript

I just found out the hard way that naming your variable arguments is a bad idea.

var arguments = 5;

(function () { 
    console.log(arguments); 
})();

Output: []

It turns out that arguments is "a local variable available within all functions" so in each new execution context, arguments is shadowed.

My question is: Are there any other such treacherous names which, like arguments, are not true reserved words, but will cause still problems?

like image 963
Rag Avatar asked Jan 03 '13 12:01

Rag


People also ask

What are valid JavaScript identifiers?

A JavaScript identifier usually starts with a letter, underscore ( _ ), or dollar sign ( $ ). Subsequent characters can also be digits ( 0 – 9 ). Because JavaScript is case sensitive, letters include the characters A through Z (uppercase) as well as a through z (lowercase).

Which of the following can not be used as valid identifier?

This is Expert Verified Answer Only alphanumeric characters (a-z, A-Z, 0-9) (i.e. letters and numerals) and the underscore(_) sign are allowed in an identification. The names of the identifiers must be unique. An alphabet or underscore must be the first character. Keywords cannot be used as identifiers.


1 Answers

Yes. Like window or document, for example. See a longer list here ("other javascript keywords").

Wouldn't recommend using any of them, even though some would work as intended.

Edit: Like mentioned in javascript.about.com, "While they are not reserved words, the use of those words as variables and functions should be avoided.". They are listing mostly the same things classified as predefined classes and objects and global properties.

Example of a problem:

var window = 5;

(function () { 
    alert(window); 
})();

the code above has unpredictable results due to fact that window is the word to refer to the window object. Firefox prevents modifications to it, so alert will still refer to window object, whereas in IE8, you'll get alert with value 5.

like image 165
eis Avatar answered Oct 06 '22 16:10

eis