user3602937
user3602937

Reputation:

simplify IF statement with multiple OR || conditions for the same variable

Here's my code

var something = "four";

if(
    something == "one" || 
    something == "two" || 
    something == "three" ||
    something == "five" ||
    something == "six" ||
    something == "seven"
){
    document.body.innerHTML = "<h1>yes</h1>";
}else{
    document.body.innerHTML = "<h1>no</h1>";
}

Is there a way to simplify the IF statement given that all the conditions regard the same variable?

DEMO

Upvotes: 2

Views: 2495

Answers (3)

Dory Daniel
Dory Daniel

Reputation: 826

let something = "four";

if ( ["one","two","three","five","six","seven"].includes(something) ) {
    document.body.innerHTML = "<h1>yes</h1>";
} else {
    document.body.innerHTML = "<h1>no</h1>";
}

Upvotes: 0

John Koerner
John Koerner

Reputation: 38087

You could always invert your check:

var something = 4;

if(
    something < 1 || 
    something == 4 || 
    something >7
){
    document.body.innerHTML = "<h1>no</h1>";
}else{
    document.body.innerHTML = "<h1>yes</h1>";
}

Upvotes: 0

Christopher Esbrandt
Christopher Esbrandt

Reputation: 1198

Try this:

var something = 4;

if([1,2,3,5,6,7].indexOf(something) > -1) {
 document.body.innerHTML = "<h1>yes</h1>";
} else {
 document.body.innerHTML = "<h1>no</h1>";
}

JSFiddle: http://jsfiddle.net/2onn6Lc2/1/

Also, please post this type of question on https://codereview.stackexchange.com/

Upvotes: 3

Related Questions