-3

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"]

Pointy
  • 405,095
  • 59
  • 585
  • 614
Loth237
  • 5
  • 2

2 Answers2

0

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
rMonteiro
  • 1,371
  • 1
  • 14
  • 37
0

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);
Ahmed Kesha
  • 810
  • 5
  • 11