2 min read views

Day14: JS Reference VS Copy

Understanding the differences between reference and copy in JavaScript, with various methods for copying arrays and objects.

Introduction: Understanding the differences between Reference and Copy in JavaScript, exploring various methods for copying arrays and objects.

Copying Primitive Data Types

let age = 100
let age2 = age
console.log(age, age2) // 100, 100
age = 200
console.log(age, age2) // 200, 100
 
let name = 'Wes'
let name2 = name
console.log(name, name2) // Wes, Wes
name = 'wesley'
console.log(name, name2) // wesley, Wes

Array Reference and Copy

const players = ['Wes', 'Sarah', 'Ryan', 'Poppy']
 
// Direct assignment creates a reference, both variables point to the same array
const team = players
console.log(players, team) // ['Wes', 'Sarah', 'Ryan', 'Poppy'], ['Wes', 'Sarah', 'Ryan', 'Poppy']
 
// Modifying team affects players
team[3] = 'Lux'
console.log(players, team) // ['Wes', 'Sarah', 'Ryan', 'Lux'], ['Wes', 'Sarah', 'Ryan', 'Lux']
 
// Using slice() method to copy array
const team2 = players.slice()
 
// Using concat() method to copy array
const team3 = [].concat(players)
 
// Using ES6 spread operator to copy array
const team4 = [...players]
team4[3] = 'heeee hawww'
console.log(team4) // ['Wes', 'Sarah', 'Ryan', 'heeee hawww']
 
// Using Array.from() method to copy array
const team5 = Array.from(players)

Object Reference and Copy

const person = {
  name: 'Wes Bos',
  age: 80,
}
 
// Direct assignment creates a reference, both variables point to the same object
const captain = person
captain.number = 99
console.log(person, captain) // { name: 'Wes Bos', age: 80, number: 99 }, { name: 'Wes Bos', age: 80, number: 99 }
 
// Using Object.assign() method to copy object
const cap2 = Object.assign({}, person, { number: 99, age: 12 })
console.log(cap2) // { name: 'Wes Bos', age: 12, number: 99 }
 
// Using JSON methods for deep copying objects
const wes = {
  name: 'Wes',
  age: 100,
  social: {
    twitter: '@wesbos',
    facebook: 'wesbos.developer',
  },
}
 
console.clear()
console.log(wes)
 
const dev = Object.assign({}, wes)
const dev2 = JSON.parse(JSON.stringify(wes))

Note

  • Both Object.assign() and spread operator create shallow copies, only copying the first level. Nested objects remain references.
  • Deep copying can be achieved using JSON.parse(JSON.stringify(obj)) or third-party libraries like lodash's cloneDeep method, but use with caution.

Related Posts

Comments