0

the function should be like function trueOrFalse(), it should not keep anything in global scope, everything has to be scoped local to the function. the returned value should be true or false and next time it should return the inverse.

1 Answers1

2

You're on the right track. A closure and a local variable is all you need.

function gen () {
    let state = false;
    return function () {
        return state = !state;
    }
}
const trueFalse = gen();

trueFalse() //true
trueFalse() //false

Regarding the comment, it's possible to do this without a closure using a property on the function itself.

function trueOrFalse () {
    return trueOrFalse.state = !trueOrFalse.state;
}
trueOrFalse() //true
trueOrFalse() //false
Moritz Roessler
  • 8,542
  • 26
  • 51