Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

316
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!