sotiristherobot
sotiristherobot

Reputation: 299

Stale closures issues in JavaScript

I am revisiting closures, and I have stumbled over the following, which I can't really get my head around, could someone please help me with the following?

function Inc(){
  let v = 0
  let p = v
  
  function value() {
    console.log('p',p)
    console.log('v', v)
  }
  
  function setValue() {  
    v += 1;
    console.log(v)
  }
  
  return [value, setValue]
}

let [value, setValue] = Inc()

value() // p 0 , v 0
setValue() 
value() // p 0, v1

Based on my understanding, closures close over the primitive value they were created with. In this case shouldn't be the value of v be also 0? What happens in setValue body that somehow updates the value in value?

Thanks!

Upvotes: 1

Views: 270

Answers (1)

Quentin
Quentin

Reputation: 943579

Closures close over variables, not values.

  • v is closed over.
  • setValue changes v
  • value reads v.

Upvotes: 1

Related Questions