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.
Asked
Active
Viewed 270 times
0

Sandeep Vattapparambil
- 124
- 1
- 10
-
4What have you tried so far? A closure, as mentioned in the title, sounds like a good start. – ASDFGerte Oct 25 '19 at 13:20
-
functions are just objects - does that help - don't need *any* variables at all – Bravo Oct 25 '19 at 13:38
-
Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Dexygen Oct 25 '19 at 14:08
-
@GeorgeJempty I wouldn't say that this is a duplicate, but rather a too broad question... – FZs Oct 25 '19 at 14:31
-
@GeorgeJempty , its not about `Closures`, but about implementing a particular logic using closures, its not a duplicate ! – Sandeep Vattapparambil Oct 25 '19 at 14:34
1 Answers
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
-
yes, but can you write it exactly as asked: `function trueOrFalse() {...}` and no other code? – georg Oct 25 '19 at 13:46
-