I've got what may be a stupid question. In the code below, the function doStuff appears to reassign myArray to an empty array, but when tried it in the console, myArray is still [2,3,4,5].
var myArray = [2, 3, 4, 5];
function doStuff(arr) {
arr = [];
};
doStuff(myArray);
console.log(myArray)// => [2,3,4,5]
Further, a function that modifies the array seems to work fine. For example:
function changeSecondIndex(arr){
arr[2] = 25;
}
changeSecondIndex(myArray)
console.log(myArray) // => [2,3,25,5]
Could someone please help me understand what's going on here? Thanks.
The entire array can be referenced using just the array name, with no index. This is useful for assigning the same value to every element or clearing all the values in the array. The syntax is dim array([lbound to] ubound).
In Javascript objects and arrays are passed by reference.
Creating an Array Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.
An item in a JavaScript array is accessed by referring to the index number of the item in square brackets. We know 0 will always output the first item in an array. We can also find the last item in an array by performing an operation on the length property and applying that as the new index number.
Your code is creating new empty array, instead you can empty existing array with length = 0
var myArray = [2, 3, 4, 5];
function doStuff(arr) {
arr.length = 0;
};
doStuff(myArray);
console.log(myArray)
Arrays are passed by reference in JavaScript. So, in your doStuff
and changeSecondIndex
functions, the arr
parameter contains a reference to myArray
.
In changeSecondIndex
, you're using that reference to access and update a property of the array. That works fine, as you can see. But in doStuff
, what's actually happening is that you are setting arr
to a new array. What that does is remove the fact that arr
was a reference to myArray
and sets it to a new blank array. That's why myArray
is not modified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With