1

I've 3 variables a,b,c

The initial values of this variables will be 'false'

I want to compare this variables only have that 'true' value.

For example,

a=true,b=false,c=true.

So I need to compare like,

if(a && c)

if, a=true,b=true,c=true,

if(a && b && c)

How can I generate this if condition dynamically?

4
  • Are you looking to generate a string representation of the JavaScript code for that if condition? Commented Jul 17, 2014 at 6:52
  • What do you mean by dynamically? You can't (or shouldn't) generate code at runtime, there is almost always a better way. Commented Jul 17, 2014 at 6:53
  • 1
    If all variables you want, for example b and c, are true, what's the meaning of writing if (b && c) {...? since this clause will always pass. Commented Jul 17, 2014 at 6:54
  • sorry, I had a mistake. Now I corrected the post Commented Jul 17, 2014 at 7:22

1 Answer 1

5

I suppose you could approach the issue with [].every() which performs a similar comparison:

if ([a, b, c].every(Boolean)) {
    // etc.
}

Here, Boolean() is a native function that will accept a value and return its boolean value.

That said, just this will cover all cases too, considering that it uses short circuiting to stop the comparison once a false value is found and is undoubtedly easier to read:

if (a && b && c) {
    // etc.
}
Sign up to request clarification or add additional context in comments.

1 Comment

No need for isTrue - the Boolean function can do that for you - [a, b, c].every(Boolean)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.