Basic JavaScript - Stand in Line

Tell us what’s happening:

Hey

I cannot understand how nextInline function mutates the array of testArr without mentioning it’s name.

Your code so far

function nextInLine(arr, item) {
  // Only change code below this line
  arr.push(item);
  return arr.shift(); 
  return item;
  // Only change code above this line
}

// Setup
let 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));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36

Challenge Information:

Basic JavaScript - Stand in Line

You appear to have created this post without editing the template. Please edit your post to Tell us what’s happening in your own words.

Hi there. Allow me to try to explain. Right now testArr was actually passed into the function nextInLine in this line.

console.log(nextInLine(testArr, 6));

It was passed into the function as the arr argument. From there any modifications on arr applied to testArr since they referred to the same location in memory.

Here is more on functions. I hope this helps. :slight_smile:

1 Like

As said, the function is called with the array as the argument. Inside the function testArr is passed to the arr parameter.

It is pass-by-value the reference to the array so any changes to the content of the object (arrays are objects) will be reflected in the original array.

Reassignments are not reflected (because it is not pass-by-reference but pass-by-value).

So the array is not really mutated, it’s just the console.log showing what the function might do to the array??

It’s 5 hours now trying to figure this out. I read a lot about functions and I’ll read more…

Thanks for your help

“Inside” the function there is no referance to testArr.
There is “outside” of the function, on the console.log(nextInLine(testArr, 6));.

I understand now this console.log but if testArr logged, i see the array is not mutated.
So… what’s the purpose of the function?

The parameter arr contains testArr because that array is passed into the function when it is called. Called with testArr

console.log(nextInLine(testArr, 6));

arr is just a different name for testArr, they are the same array.

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

function nextInLine(arr) {
  return arr === testArr
}

console.log(nextInLine(testArr)); // true
console.log(nextInLine([1, 2, 3, 4, 5])); // false

We call the log() function which calls nextInLine() with testArr and 6 as it’s parameteres (replacing arr and item) and then logs the result.

The array IS mutated after this cause…we called nextInLine() through console.log().

I think I got it…

Thank you

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