20
function whatTheHeck(obj){
  var arr = []

  for(o in obj){
    arr.concat(["what"])
  }

  return arr
}

whatTheHeck({"one":1, "two": 2})

The concat function completely fails to do anything. But if I put a breakpoint on that line in Firebug and run the line as a watch it works fine. And the for loop iterates twice but in the end arr still equals [].

1
  • Actually even without the loop it still fails. The only thing that works is to say straight return [].concat(["what"]). Something is very wrong with the world. Commented Nov 1, 2011 at 5:56

1 Answer 1

47

Array.concat creates a new array - it does not modify the original so your current code is actually doing nothing. It does not modify arr.

So, you need to change your function to this to see it actually work:

function whatTheHeck(obj){
  var arr = [];

  for(o in obj){
    arr = arr.concat(["what"]);
  }

  return arr;
}

whatTheHeck({"one":1, "two": 2});

If you're trying to just add a single item onto the end of the array, .push() is a much better way:

function whatTheHeck(obj){
  var arr = [];

  for(o in obj){
    arr.push("what");
  }

  return arr;
}

whatTheHeck({"one":1, "two": 2});

This is one of the things I find a bit confusing about the Javascript array methods. Some modify the original array, some do not and there is no naming convention to know which do and which don't. You just have to read and learn which work which way.

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

2 Comments

Woah, that was really stupid of me. Where was I when that was explained somewhere? Some things modify your objects and some make new ones and I just assumed...
Also note that a basic for-in loop on an object will loop through inherited properties in addition to the ones that were set manually. So a for-in like this should check that o is one of the properties that was set "manually" on obj (i.e. use if (!obj.hasOwnProperty(o)) continue; before the push).

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.