Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing Arrays in Javascript

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.

like image 927
EFH Avatar asked Jun 07 '16 20:06

EFH


People also ask

How do you reference an array?

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).

Are arrays by reference in JavaScript?

In Javascript objects and arrays are passed by reference.

How do you represent an array in JavaScript?

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.

Can you index an array in JavaScript?

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.


2 Answers

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)
like image 147
Nenad Vracar Avatar answered Sep 29 '22 00:09

Nenad Vracar


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.

like image 30
Rocket Hazmat Avatar answered Sep 28 '22 23:09

Rocket Hazmat