Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript, how can this function possibly return an empty array?

Tags:

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 [].

like image 490
Moss Avatar asked Nov 01 '11 05:11

Moss


People also ask

Can you return an empty array?

To return an empty array from a function, we can create a new array with a zero size. In the example below, we create a function returnEmptyArray() that returns an array of int . We return new int[0] that is an empty array of int . In the output, we can get the length of the array getEmptyArray .

How many ways we can empty an array in JavaScript?

4 Ways to Empty an Array in JavaScript.

Does an empty array return true JavaScript?

Because Array is type of object , the fact that an empty Array is conversed to true is correct.


1 Answers

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.

like image 160
jfriend00 Avatar answered Nov 11 '22 14:11

jfriend00