## Submodule 6.2: Making Decisions

• Comparison operators
• If statements
• Logical operators

### The if statement

The if statement is a conditional expression in JavaScript.

Conditionals are easy to understand since they have the same meaning in JavaScript with what they have in English.

They actually say: " if something is true, do the following"

if (expression) {    //this code runs if expression evaluates to true}
##### Example

The code below is a combination of the if statement with an operator.

What it does, is that it takes the value that the user enters into the prompt popup window, passes it in the myNum variable and checks whether this number is smaller than 5. If this is true, like if our number was 4, it then goes and writes what we have defined in the document.

Notice the syntax: the expression is inside the "parenthesis", and the block of code you want to execute on true is enclosed by "curly braces" which look like this: { }

<!DOCTYPE html><html lang="en">  <head>     <title>The if statement </title>   </head>   <body>     <h3> The if statement</h3>     <script>          var a = 5;          var myNum;          myNum = prompt("Write a number?");          if (myNum < a) {            document.write("You wrote the number " + myNum + ". This number is less than " + a +".")          }       </script>   </body></html>

Exercise

1. Open your editor, create a new file and save it as exersice06.2.0if.html in the folder "yourNameWEB2JS".
2. Copy the above code and paste it in the new file.
3. Save the file and preview it in your editor or your browser.
4. Check your code by inserting the numbers 4,5,6 in the prompt window. What do you see?

The code works only in the case where 6>5. We will improve it on the next page.