Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I think that array is reference types but when i run this code the result seem not like that

let a = [1, 2, 3]
let b = a
a = [1, 2]
console.log(b)

I expected that the result will be 1, 2 but it is 1, 2, 3

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You’ve changed the pointer of the variable a to a new array, but the old array still exists because b is still pointing to it. All you’ve done is reassign the array that the variable a is now pointing to.

This is working as expected. You’ll get the result you were trying to achieve by mutating the array a is pointing to instead of completely reassigning it. Ie

let a = [1, 2, 3]
        let b = a
        a.pop()
        console.log(b)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading