When coding, if/else statements can be very useful. They allow code to be carried out based on the terms we set. Basically, we are stating that IF something is true, then the program should carry this function out, if it’s not true, so else, it carries a different statement out. We use if/else statements in order to run code based on if a statement is true or false.
Example:
let number = prompt (“Enter a number”);
if (number != 0) {
alert (‘Not zero’);
}else{
alert (Number is zero);
{
With this function, if a person enters a number other than zero, then the program will alert “Not Zero”. We know this because we said if (number != 0), != means “doesn’t equal”. However, if it is zero, then the program will return “Number is zero”.
With if/else statements you can have many different elements, stated by the term “else if”. You can use as many as you want in order to do what you want to. It looks like this:
let color = prompt (“Pick a color. Pink, red, blue.”);
if (color = ‘Pink”) {
alert (‘You chose pink);
}else if (color =’Red’){
alert (‘You chose red’);
}else if (color =’Blue){
alert (‘You chose blue’);
}else{
alert (“You did not choose a valid color”);
Leave a Reply
You must be logged in to post a comment.