THis is my code
let a = ["a","b","c"]
let b = "dd"
let c = a
c.push(b)
console.log(a);
console.log(c);
But i want that when i log "a" it returns ["a","b","c"] And when i log "c" it returns ["a","b","c", "d"]
THis is my code
let a = ["a","b","c"]
let b = "dd"
let c = a
c.push(b)
console.log(a);
console.log(c);
But i want that when i log "a" it returns ["a","b","c"] And when i log "c" it returns ["a","b","c", "d"]
Array/object values are copied by reference instead of by value. So, if you do let c = a
the c
points to the same array object as a
You can use Spread Operator (Shallow copy) to make a new copy of the array.
let a = ["a","b","c"]
let b = "dd"
let c = [...a]
c.push(b)
console.log(a);
console.log(c);
Be aware this does not safely copy multi-dimensional arrays.
let a = [["a"],["b"]]
let c = [...a]
let b = "dd"
c[0].push(b)
console.log(a);
console.log(c);
// [["a", "dd"], ["b"]]
// [["a", "dd"], ["b"]]
// They've both been changed because they share references
Try this to make new ref
let a = ["a","b","c"]
let b = "dd"
let c = [...a]
c.push(b)
console.log(a);
console.log(c);