Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
Keeping references without modifying the state in javascript

I have this impure code that prints two equal messages

class P {
   constructor() {
        this.x  = 0
        this.y  = []
   }
}

const incrX = (p)   => { p.x = p.x + 1 ; return p }
const incrY = (p,q) => ( p.y.push(q)   ; return p }

const ps = [ new P() , new P() ]

const result = ps.map( (_,i) => i === 0 ? incrY(ps[i],ps[i+1]) : incrX(ps[i]) )

console.log( result[0].y[0] )
console.log( result[1] )

But using pure functions, the prints are not equal, because ps[0].y[0] keeps an old reference

class P {
   constructor() {
        this.x  = 0
        this.y  = []
   }
}

const incrX = (p)   => ({ ...p , x : p.x + 1 })
const incrY = (p,q) => ({ ...p , y: [ ...p.y , q ] })

const ps = [ new P() , new P() ]

const result = ps.map( (_,i) => i === 0 ? incrY(ps[i],ps[i+1]) : incrX(ps[i]) )

console.log( result[0].y[0] )
console.log( result[1] )

Is there an way to keep references using something similar to the pure version ? Maybe using an array that stores references to references, is this even possible in javascript ?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!