-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
  • 389,373
  • 58
  • 564
  • 602
Loth237
  • 5
  • 1

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
  • 711
  • 10
  • 26
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
  • 789
  • 4
  • 10