1

When I assign anotherArrayList = arrayList, anotherArrayList is a pointer to arrayList. So why this does not work when I empty the arrayList.

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; 
var anotherArrayList = arrayList;  

arrayList[1] = '15';

console.log(arrayList); // output: [ "a", "15", "c", "d", "e", "f" ]
console.log(anotherArrayList); // output: [ "a", "15", "c", "d", "e", "f" ]

arrayList = []; 
console.log(arrayList); // output: []
console.log(anotherArrayList); // output: [ "a", "15", "c", "d", "e", "f" ] 
5

3 Answers 3

2

By assigning a new array, the old object reference gets a new reference to the empty array.

You could assign zero to the length property which empties the object reference as well.

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f'],
    anotherArrayList = arrayList;

arrayList[1] = '15';

console.log(arrayList);        // [ "a", "15", "c", "d", "e", "f" ]
console.log(anotherArrayList); // [ "a", "15", "c", "d", "e", "f" ]

arrayList.length = 0; 
console.log(arrayList);        // []
console.log(anotherArrayList); // [] 

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't answer he question.
2

It doesn't empty your other array because you're not actually clearing/emptying it, instead you are creating a new empty array in memory, which arrayList will point to, whereas anotherArrayList will still point to the full array.

Instead, to empty the array itself, you can use the .length property: arrayList.length = 0

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; 
var anotherArrayList = arrayList;  

arrayList[1] = '15';

console.log(arrayList); // output: [ "a", "15", "c", "d", "e", "f" ]
console.log(anotherArrayList); // output: [ "a", "15", "c", "d", "e", "f" ]

arrayList.length = 0; 
console.log(arrayList); // output: []
console.log(anotherArrayList); // output: []

Comments

0

Array and objects are non-primitive data-type in javascript. When a variable is assigned with reference to a non-primitive data-type, the copy of memory location is stored in that new variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.