Need help breaking down how this function works

Hey all, I am currently working through the Javascript section and can’t quite understand how this function works:

function nextInLine(arr, item) {

// Only change code below this line

return arr.shift();

// Only change code above this line


// Setup

const testArr = [1, 2, 3, 4, 5];

// Display code

console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6));
console.log("After: " + JSON.stringify(testArr));

My question is: how do the parameters in the function nextInLine impact the testArr array? I get the concept of push() and shift(), but my brain isn’t wrapping around how the console displays changes to that array. My apologies if this is an obvious answer!

In JS, arrays are passed into a function “by reference”, which means that any changes to the array inside of the function remain after the function is completed. In other words, the function is manipulating the array directly and those changes are permanent and persist even after the function has ended.

So after you have changed the array inside of the function you can see those changes when you console log it after the function.

You simply return the shifted value, which is no longer part of the array
Also, the array has just been shifted 1 position to the left

1 Like

I see, I think it was getting hung up on the parameters. So it appears the parameters are just placeholders then. I got hung up on not explicitly seeing “testArr.push();” or “testArr.shift();”. Thank you!

In this case, since it is pass by reference, it is just another name for the array. The variable name testArr outside of the function and the variable name arr inside of the function both point to the exact same array.

On the other hand, if the item you are passing into the function is a number then that is being passed “by value” and it is a copy of the original value.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.