Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Can a JavaScript variable be true N times and then false?

Is it possible to have a JavaScript variable that, when used by other code, works as a boolean (a single bit of memory) but has an internal state so that it is true the first N times that the value is read, and then false?

In other words, is it possible to define trueNTimes so that the following code prints yes 3 times and then prints no 2 times?

let true3times = trueNTimes(3);
for (let i = 5; i; --i)
    if (true3times) console.log('yes');
    else console.log('no');

As as a side note, it can be done in C++ (by defining struct TrueNTimes with operator bool) like this:

#include <iostream>
struct TrueNTimes {
    TrueNTimes(uint const N) : n(N) {}
    operator bool() {
        if (n) {
            --n; 
            return true;
        }
        return false;
    }
private:
    uint n;
};

int main() {
    TrueNTimes true3times(3);
    for (uint i = 5; i; --i)
        if (true3times) std::cout << "yes\n";
        else std::cout << "no\n";
}

The C++ compiler finds a variable of type struct TrueNTimes where a bool is needed and will therefore use the provided TrueNTimes::operator bool.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Yes, in JavaScript you would define valueOf:

function trueNTimes(n) {
    return {
        valueOf() {
            if (n) {
                --n; 
                return true;
            } else 
                return false;
        }
    }
};

let true3times = trueNTimes(3);
console.log(true3times + ' ' + true3times + ' ' + true3times + ' ' + true3times + ' ' + true3times);

As in JavaScript objects are always truthy, you need to really compare this variable in order to trigger the valueOf algorithm:

function trueNTimes(n) {
    return {
        valueOf() {
            if (n) {
                --n; 
                return true;
            } else 
                return false;
        }
    }
};

let true3times = trueNTimes(3);
for (let i = 5; i; --i)
    if (true3times == true) console.log('yes');
    else console.log('no');

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!