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!

Ry-
  • 218,210
  • 55
  • 464
  • 476
Viewsonic
  • 827
  • 2
  • 15
  • 34
  • https://codepen.io/philsco/pen/BNwgRm This should put you on the rights track. – Wiktor Zychla Dec 11 '19 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. – Bergi Dec 11 '19 at 22:33
  • Like a generator? – Dave Newton Dec 11 '19 at 22:33
  • In your case you don't need to keep track of it outside of the function`a = count(0); b = count(a); c = count(b)` Just pass in a parameter. – Train Dec 11 '19 at 22:34

1 Answers1

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
Ry-
  • 218,210
  • 55
  • 464
  • 476