Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

321
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda