Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
JavaScript closure question with counter example

Consider we have follow snippets:

function Counter() {
  let count = 0
  
  function inc() {
    count += 1
  }
  
  function dec() {
    count -= 1
  }
  
  function getCount() {
    return count
  }
  
  return { getCount, inc, dec, count }
}

const counter = Counter()
counter.inc()
counter.inc()

console.log(counter.getCount()) // 2
console.log(counter.count) // 0

I am wondering why using function getCount() and directly return count variable shows different result. In my opinion they both reference the same count address, and after inc() calls its value should be altered accordingly.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

return { getCount, inc, dec, count }:

  1. Creates a new object
  2. Copies the current values of those four variables onto properties with the same names
  3. Returns that object

When you change the value of the count variable you do not change the value of the count property.

about 4 years ago · Juan Pablo Isaza Relatório

0

The reason is because when you do counter.count, you are getting the count value off the of the new object you returned. That count is actually a copy of the value at the time it was created and will never get updated.

If instead, you create a class and use this.count instead, it'll always be updated.

class Counter {
  constructor() {
    this.count = 0;
  }
  
  inc() {
    this.count += 1;
  }
  
  dec() {
    this.count -= 1;
  }
  
  getCount() {
    return this.count;
  }
}

const counter = new Counter();
counter.inc()
counter.inc()

console.log(counter.getCount()) // 2
console.log(counter.count) // 2

Or, if you want to do it the more old-school way:

function Counter() {
  this.count = 0
  
  function inc() {
    count += 1
  }
  
  function dec() {
    count -= 1
  }
  
  function getCount() {
    return count
  }
  
  this.inc = inc;
  this.dec = dec;
  this.getCount = getCount;
  
  return this;
}

const counter = Counter()
counter.inc()
counter.inc()

console.log(counter.getCount()) // 2
console.log(counter.count) // 2

Or, you could make count and object with some value that would get updated:

function Counter() {
  let count = { value: 0 }
  
  function inc() {
    count.value += 1
  }
  
  function dec() {
    count.value -= 1
  }
  
  function getCount() {
    return count.value
  }
  
  return { getCount, inc, dec, count }
}

const counter = Counter()
counter.inc()
counter.inc()

console.log(counter.getCount()) // 2
console.log(counter.count.value) // 2

Though that last one is a bit silly for this particular use-case.

about 4 years ago · Juan Pablo Isaza Relatório

0

Mostly because count that you are returning from function is a copy of variable (value to be more accurate) and getCount is a function, which refers to reference of a count variable. More you can learn here.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda