This week I was chasing a javascript bug, which ended up in the following lines:
1 | ... |
Can you spot the issue?
This line mixes declarations and assignments:
1 | var tag = node = Ext.apply({...}) |
The author thought they were initializing two local vars tag and node. Unfortunately, Javascript is a bit surprising here.
Take the following example:
1 | function test(){ |
- Javascript starts by evaluating
b = 2. This is an assignment of the value2to the variableb. - Because
bdoes not exist, Javascript will actually create a brand new global variable b, and attach it to the current context, in this casewindow. This is usually something you don’t want to do, and it made bug finding much trickier. - The rest of the expression hides the problem. The assignment returns the value that was just assigned, so the expression
var a = b = 2now becomesvar a = 2. This correctly creates a local variableacontaining the value2, hiding the damage it has created withbin the global scope.
Note that strict mode fixes this and throws a ReferenceError exception.