JavaScript #7 – If…else Statement

When you write your program, you may want to check condition statement. It is unimportant, what you want to check – variables or expressions. It usually looks the same. For example, we want to check if a variable called age is equal to 20:

Write this code to file or directly in your console, type your age in prompt box and check result.

So, let me explain this code to you. In the first line, we declared age variable, that took value from the prompt box. In a second line, we write the conditional statement, that check if age is equal to 20. Three signs of equality mean, that age must be exactly this same type as right part of the statement. Moreover, the variable must be this same value. With two signs of equality, we can check only value – not type of value. For instance:

Check this code in your browser. As you see, when you type e.g 20, console throw “You are 20” and in next line “string”. So, we compared string with number and browser thinks that is true. So, safer and rather better to use is three signs of equality, but they are not always necessarily.

Ok, but what is else. Block of code after else runs when if…statement was false. When you type other value than 20, a browser will run else block and show “You are not 20!” in the console.

You can also compare expression with string, state (true or false) and object. For example

In this case, we check if a check box is checked. We skip equality signs because a check box (and radio input) can hold only two values. True or false. By default, when we skip this signs, browser look after true value in expressions.

By the way, we have one more notation of conditional statements. I write about else if. Look at this code

Save this to file and execute. When you type John or Lucy as name, you got the right message in console. If you put another name, you got the log from the else block.

All in all, you probably see how powerful condition statement is. In the next article, I will show you, how to use a switch statement, which is very similar to else…if but more expanded. If you have any question or something is unclear to you write in the comments section, I will help you.

 

Herbaciarz

 

Leave a Reply

Your email address will not be published. Required fields are marked *