Home > Enterprise >  is const variable in javascript function initialized every time when it called or just once?
is const variable in javascript function initialized every time when it called or just once?

Time:05-20

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 ?

CodePudding user response:

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));

  • Related