Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var i = [0] in a for loop, then incremented i++ - why does it work?

In a book that I'm reading (JavaScript & JQuery - Interactive Front End Development by Jon Duckett) there's an interesting error or (at least I think so) which doesn't stop the code from working:

for (var i = [0]; i < options.length; i++) {         
   addEvent(options[i], 'click', radioChanged);       
}

This is a part of script that loops through all radio buttons in a form and attaches an event listener (it doesn't really matter what it does).

But...

  1. Why is i initialised as an array at all?

  2. Why does the incrementation work?

  3. Why does the whole loop work?

Of course if you replace var i = [0] with var i = 0 the code still works.

When you add some alerts to check the value of i in each iteration of the loop and the type of i, at the second iteration type of i changes from object (after all in the first iteration it is an array) to number. That's a kind of implicit type conversion I have never come across so far (and google don't help much). Can anyone explain what's going on under the hood?

for (var i = [0]; i < options.length; i++) {         
   addEvent(options[i], 'click', radioChanged);  
   alert(i); // --> 1   2   3 ...
   alert(type of i); // --> object   number   number ...
}
like image 697
Tadek Avatar asked Sep 03 '15 18:09

Tadek


1 Answers

The spec says (§ 11.3.1) that the ++ operator converts its operand to a number before incrementing:

  1. Let oldValue be ToNumber(GetValue(lhs)).

When called on an object, the GetValue internal operation will call toString(), which, for an array, will join its elements, returning '0'.

like image 187
SLaks Avatar answered Oct 13 '22 22:10

SLaks