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...
Why is i initialised as an array at all?
Why does the incrementation work?
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 ...
}
The spec says (§ 11.3.1) that the ++
operator converts its operand to a number before incrementing:
- 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'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With