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

123
Views
JavaScript local static varible like in C/C++

Below is some code demostrates static local variable in C/C++. Counter would be added for each time when btnTestOnclick is called -- counter can be accumulated.

void btnTestOnclick()
{
    static int counter = 0;
    counter++;
}

But in the below JS code,

function btnTestOnclick() {

        class temp{
        static counter=0;
        };
        console.log(temp.counter);
        temp.counter+=1;
}

This temp.counter can't be accumulated, every time it's 0. I know moving the temp class out of the function would work, but this class is supposed to logically be local since only btnTestOnclick would use it.

How do you think about it?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need a closure where the persistent variable only visible to btnTestOnclick is created. Use an immediately-invoked function expression.

const btnTestOnclick = (() => {
  let counter = 0;
  return () => {
    counter++;
    // do other stuff with counter?
  };
})();

That said, personally, I consider IIFEs to be slightly outdated nowadays. If the section of code you're writing this in is such that you're afraid that adding another variable to its scope (counter) would make things more confusing than would be ideal, it's probably time to extract some of that code into a standalone module.

let counter = 0;
export const btnTestOnclick = () => {
  counter++;
  // do other stuff with counter?
};

where the above file contains nothing else (and thus counter is clearly scoped only to the exported btnTestOnclick)

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!