An if statement is a conditional statement that if proven to be true, performs a block of code inside of it(A conditional statements is a boolean that either stores the value of true or false). If the conditional statement turns out to be false, the if statement can run another block of code. If statements are a basic way to let a program make different decisions based on the input going in the conditional statement. The syntax for a basic if statement looks like the following:
if(5 < 4){ console.log("True") }else{ console.log("False") }
If statements can be used without the else statement. That would mean that if the condition were to be false, nothing would happen and the program would continue on to the next block of code.
You can also use if statements together by nesting them inside of each other. This allows for different paths of code to go down based on multiple conditional statements instead of only one. To use the nested if statement, first add a singular if statement. Inside of the first block of code, you can insert another if statement. That is what the code block below looks like, but you can even nest if statement in the else block of the loop. You can add as many nested if statements as you want, but if you go crazy with it, it is very easy for it to get confusing.
var number = prompt("Enter a number"); if(number < 100){ if(number < 50){ alert("You win!"); }else{ alert("You lose!"); } }else{ alert("You lose!"); }
However, using the keyword “else if” in an if statement is most of the time better than nesting them. To use an if else statement, start out the same as a basic if statement and then after the first closing curly brace, enter the keyword "else if". After the else if you can add another conditional statement with a whole new block of code under it. You can use as many if else statements as you want. The syntax for an if else statement looks like the following:
var color = prompt("Enter a color"); if(color == "red"){ console.log("roses"); }else if(color == "blue"){ console.log("water"); }else if(color == "yellow"){ console.log("bananas"); }else{"making babies"}