Crocsx
Crocsx

Reputation: 7609

How to reset an array that is outside function scope

I don't know exactly how to title this but here is an exemple

I pass an array to a function, and I want that all the changed inside the function are applied to the array that was passed by ref (event the []) =>

var myArray = [1,2,3,4];
function resetter(arr){
   arr = []
}
resetter(myArray); // still  [1,2,3,4] because I assign a new object

but I want that changed to be applied to my array I passed as a reference

var myArray = [1,2,3,4];
function resetter(arr){
   arr.length = 0;
}
resetter(myArray); // [] but is this clean ?

are there any other way ?

Upvotes: 1

Views: 263

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36574

If two variables have same reference it means that modifying(changing property) one of them will change another. It doesn't mean that assigning one with new value will change another value.

You can use splice()

var myArray = [1,2,3,4];
function resetter(arr){
   arr.splice(0,arr.length)
}
resetter(myArray);

console.log(myArray)

Consider if you want to change the array to whole new array not just []. You can pass another array using spread operator to splice()

var myArray = [1,2,3,4];
function resetter(arr, newArray){
   arr.splice(0,arr.length,...newArray)
}
resetter(myArray, ['str1','str2']);

console.log(myArray)

Upvotes: 3

Related Questions