Reputation: 85
I was going through the Javascript map function, and stuck at the loop syntax. It is difficult to figure out the o placed after comma. Can anybody help me figure it out. Also what is the terminating condition for loop ?
Array.prototype.mymap = function (callback) {
var obj = Object(this);
if (obj.length === 0) return null;
if (typeof(callback) === 'undefined') return null;
for (var i = 0, o; o = obj[i]; i++) {
obj[i] = callback(o);
}
return obj;
};
Upvotes: 0
Views: 145
Reputation: 522016
for (var i = 0, o; o = obj[i]; i++) {
obj[i] = callback(o);
}
This is the same as:
var i = 0,
o;
while (o = obj[i]) {
...
i++;
}
Which means, it declares the variable o
, which is initially set to undefined
. During each loop iteration, obj[i]
is assigned to o
. When obj[i]
results in undefined
(because i
is beyond the length of the array), the expression o = obj[i]
results in undefined
, which terminates the loop.
Actually, this loop implementation has a bug: it terminates whenever any array value is falsey; which is probably not desired.
Upvotes: 6