0

How can I declare a variable inside a JavaScript function, so the following behavior happens?

The initialization should happen once.

function count() {
  let_special count = 0;
  count++;
  if (count == 3) {
    count = 5;
  }
  return count;
}

let a = count(); // a = 1
let b = count(); // a = 2
let c = count(); // a = 5
let d = count(); // a = 6
let e = count(); // a = 7

If I remember correctly, there was a way to do that but right now I can't find it on Google.

Thanks!

4
  • codepen.io/philsco/pen/BNwgRm This should put you on the rights track. Commented Dec 11, 2019 at 22:29
  • 1
    Quite simple: declare it outside the function. Everything else (from IIFE over static property of the function object to global undeclared variable) really is just a workaround. Commented Dec 11, 2019 at 22:33
  • Like a generator? Commented Dec 11, 2019 at 22:33
  • In your case you don't need to keep track of it outside of the functiona = count(0); b = count(a); c = count(b) Just pass in a parameter. Commented Dec 11, 2019 at 22:34

1 Answer 1

0

Declare a variable inside a JavaScript function that keeps its value on multiple calls to that function

You can’t. But you can declare a variable outside a function.

let count = 0;

function counter() {
  count++;
  if (count == 3) {
    count = 5;
  }
  return count;
}

let a = counter(); // a = 1
let b = counter(); // b = 2
let c = counter(); // c = 5
let d = counter(); // d = 6
let e = counter(); // e = 7

Even if that variable is inside another function.

function makeCounter() {
  let count = 0;

  function counter() {
    count++;
    if (count == 3) {
      count = 5;
    }
    return count;
  }

  return counter;
}

let count = makeCounter();
let count2 = makeCounter();
let a = count(); // a = 1
let b = count(); // b = 2
let c = count(); // c = 5
let d = count(); // d = 6
let e = count(); // e = 7

let f = count2(); // f = 1
let g = count2(); // g = 2
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.