简体   繁体   中英

How to write a function in javascript which returns true or false as alternating when its invoked without keeping global variables using closure?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM