0

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;
};
3
  • 2
    it just declares another variable named o Commented Nov 15, 2016 at 15:31
  • What error are you seeing? Commented Nov 15, 2016 at 15:31
  • Hi, AlgoreRythm, I am not seeing any error, I just want to understand that. Commented Dec 2, 2016 at 9:03

1 Answer 1

5
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks torazburo and deceze, Got it now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.