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

319
Visualizações
is const variable in javascript function initialized every time when it called or just once?

I'd like to code something like this.

function cokeDispencer(id) {
  const dict = {1:"sprite", 2:"pepcy", ...} // Some JSON. It might be bigger. 
  return dict[id];
}

Of course, dict[id] is much simpler way to do the same, but I want put the dict object inside of function so that no other function can access to this dict object. What I'm wondering is that the object dict is initialized everytime it called. As I know, function written in C/C++ initalize it's local variable everytime it called except static variable. If then, is there a way to initalize const variable just once like static variable C/C++?

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

0

Yes, you're creating a new dict object every time that function runs.

You can make an IIFE instead - a function that runs immediately and "closes" over the object and can return a function that accesses the desired property.

const cokeDispencer = (() => {
  const dict = {1:"sprite", 2:"pepcy"} // Some JSON. It might be bigger. 
  return id => dict[id];
})();
console.log(cokeDispencer(1));

This is almost the same thing as

const dict = {1:"sprite", 2:"pepcy"} // Some JSON. It might be bigger. 
const cokeDispencer = id => dict[id];

console.log(cokeDispencer(1));

except that the IIFE makes sure that only the cokeDispener function has access to the object.

If you want to create the object only the first time the function is called, and not before, you could use a pretty similar technique to assign to a variable scoped only to the function if needed.

const cokeDispencer = (() => {
  let dict;
  return (id) => {
    if (!dict) {
      dict = {1:"sprite", 2:"pepcy"} // Some JSON. It might be bigger. 
    }
    return dict[id];
  };
})();
console.log(cokeDispencer(1));

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