Mistakes On Chain Assignment In javascript

Sep 30, 2011 No Comments by Mahdi Pedram

One common mistake that I see developers do is exposing a variable to the Global object in chain assignment.

first I let's see how can you expose a variable to the Global object by accident.

 
function test(){
a =12; // var is missing
return a;
}
test();
 

By missing the keyword var even though variable a is inside of the function but "a" will be exposed to the global object(Window Object).

now you would say I already know this and I will not miss the var keyword.

this is a common mistake that I've see programmers do and I've done it in the past.
javascript is not PHP or any other scripting language.

 
function test(){
  var x = y = 2;
}
 

Now in this case "x" is local variable, but "y" become a global variable.
this is because of right-to-left evaluation so when y = 2 there is no var to be set for it so it become a global variable.

to prevent of having such a design flaw. use var all the time.
the correct version would look like

 
function test(){
  var x,y;
  x = y = 2;
}
 
javascript

About the author

I'm Web Developer , I spent most of my time on programming web applications ,I'm both Front-end , Back-end Developer . Coding is part of my life , I don't do programming for life , I am alive to Code
No Responses to “Mistakes On Chain Assignment In javascript”

Leave a Reply