No, it does not. It will receive a value when we call it. Down below:
nextInLine(testArr, 6)
When we call the function, we are passing the array called “testArr”. Inside our function, that is saved as the array “arr”. Also, the number 6 is stored in the variable “item”. Those are the names we will use inside the function.
- The function that we have to use has a different defined arrray while the testArr given below runs in the compiler. Could you please explain are the two arrays different or the same?
They are the same. The array in the function will be whatever is passed when we call the function. In the case of arrays (and objects), if we change it inside the function it also gets changed outside the function. With an array, what we are really passing is the memory address (reference). It’s like if I had the address to my house written on a piece of paper. If I want you to paint my house, I can make a copy of that piece of paper. There are two pieces of paper but they both pointing to the same house. If you paint the house at the address on your piece of paper, the house at my address gets painted because they are the same. There are two pieces of paper with addresses on them, but they are the same address and point to the same house.
Outside the function, the array’s address is stored in the variable “testArr”. When we pass that array, inside the function, that address/reference is copied into that variable “arr” for use inside the function. But it is the same address, pointing to the same place in memory where that array is stored. There is only one array. Truly copying an array (creating a new array in a new section of memory) takes a little work in JS.
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6));
console.log("After: " + JSON.stringify(testArr));
The function console.log outputs to the console. The function JSON.stringify converts your array into text. Normally you don’t need to do that to log, but there might be a race condition making that necessary (don’t worry about that for now).
The purpose is to show you that when you pass an array, changes in the function affect the original (just like my house paining example). With reference types (arrays, objects, etc) you’re really passing the address so the array referenced in the function is the same as the one outside the function. (This is true of reference types, not primitives like number, boolean, string, etc.)
Line 1 shows you the array before.
Line 2 calls the function and shows the return value.
Line 3 shows that the array outside the function got changed by what was done inside the function.
Don’t feel bad if this is confusing. A lot of people get tripped up on this. I’ve even known intermediate JS developers who weren’t completely clear on this.