yoonsi yoonsi - 1 month ago 14
Javascript Question

Why do these ways of returning arrays differ in Javascript?

I have two examples:

function myFunction(arr, size) {
// Break it up.
var newArray = [];

var tempArray = arr.splice(0,1);
newArray.push(arr.splice(0,1));
console.log(newArray);

return arr;
}

myFunction(["a", "b", "c", "d"], 2);


And this one:

function myFunction(arr, size) {
// Break it up.
var newArray = [];

var tempArray = arr.splice(0,1);
newArray.push(tempArray);
console.log(newArray);

return arr;
}

myFunction(["a", "b", "c", "d"], 2);


The main difference being the line:

newArray.push(arr.splice(0,1)); // Or newArray.push(tempArray);


Why does the first example return Array[1] and the second example return ["a"]?

I was expecting to get ["a"] regardless of which way I went, can someone possibly help me understand what is happening here?

I was just trying to take the first element of the array by splicing (which I believe returns an array of the removed elements) and push this array onto my "newArray" so I can ultimately have an array containing nested arrays holding each character. I.e. [["a"],["b"],["c"]...]

EDIT: Please ignore the "size" parameter.
EDIT2: Sincere apologies. I'm not worried about the return statement. Stupid of me to forgot to mention. I'm looking at my console.log output. When I run the script and look at the console, that's when I'm getting Array[1] or ["a"].

Answer

This is the most important information you need to have in mind: splice changes the original array (read this: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice).

So, let's see your first function. This line:

var tempArray = arr.splice(0,1);

Changes arr, as expected. But, when you do this in the next line:

newArray.push(arr.splice(0,1));

You are changing arr again!

Your second function, on the other hand, changes arr just once:

var tempArray = arr.splice(0,1);
newArray.push(tempArray);

In a nutshell: just count how many times you have a splice in your first function (2 times, changing the original array twice) and how many times you have a splice in your second function (1 time, changing the original array only once).

EDIT: regarding the console.log, newArray is an array with an array, and that's why sometimes you see Array[1]. Do this:

console.log(newArray[0]);

And now you'll see ["a"], ["b"] or whatever.