Skip to content

Simple if Statement

Question

Which direction should I take?

selection


The if Statement

1
2
3
4
// Basic "if" statement
if (some condition) {
    // do something brilliant
}

What is "some condition?"

  • After the if comes a boolean expression => something true or false
  • All equality and relational operators can be used.

simple if statement

Which ones are boolean expressions?

(count === 5)
(name = "fred")
(3 < 10)
(10 * 20)
(6 < 5)
(true)
(count = 5)
(false)
(Number("12.99"))
("Bill" > "bill")
(1000)

Building conditions in a if statement.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Boolean conditions let count = 5;
if (count === 5) {
    // count IS 5 so I'll do this:
    document.write("The count is 5");
 }

 if (count < 10) {
     document.write("The count is less than 10");
 }

 if (typeof(count) === "number") {
     document.write("The count is a number");
 }

 if (count >= 6) {
     // Will this run?
     document.write("count is >= 6");
 }

Debugging if Statements

Always key in the skeleton of an if first, ensuring that everything is aligned properly.

1
2
3
if () {

}

Next work with the condition within the parentheses. Test the condition with an alert() , document.write(), or console.log() with some simple text such as: "Branched True"

1
2
3
4
if (count === 5) {
    alert("Branched True");
    //Alternatively you can use console.log("Branched True");
}

Then, working again one line at a time, begin to build the actual contents of the conditional block as specified in the program's specifications.

1
2
3
4
if (count === 5) {
    //alert("Branched True");
    document.write("The total is 5.");
}

If an if statement is not working right, there are in general three places to look for the problem.

  • Look above the if statement and find out what is in the variable(s) being used in both the condition and within the conditional block. Clearly, if those variables don't have in them what you think they have in them, the if statement will not appear to be correct. Use alert() or console.log() statements on those variables to see their contents.

  • Examine the condition itself to make sure it is correctly stated. Watch out for accidentally using the assignment operator = instead of equality ===.

  • Examine the program statements within the conditional block to see if they are working as intended. Placing some alert() or console.log() statements at various points within the conditional block can be useful here.


Console log statements

We've learned how to use the developer tools to help discover errors in our code. The console can also be very useful in debugging programs. You can log information to the console using a console.log() statement. Use this in place of the alert() or document.write() statements shown above.

1
2
3
if (count === 5) {
    console.log("count does indeed equal 5");
}
That code will display a message in the developer tools console

console log output

Best Practice

Always remove console.log() statements prior to submitting projects and labs. Projects and labs are your production code. And it's never a good idea to leave debugging statements in production code. You may inadvertantly leave information in your log statements that the public should not see.


Checking for a number

Validating user input is something we haven't done yet. However, we should always check user input before doing any logic. We don't ever want to assume the user enters the correct information! Now that we know how to use if statement, we can add a simple validation to check for numbers with the isNumericfunction (which is built into our course website).

The isNumeric function checks to see if the input is capable of being converted to a number. It returns true for something that can be converted to a number, and false if it can't. It also returns false if the user entered nothing at all.

It should be placed immediately after the input is received and before your convert input with the Number() function.

Check if a value is a number

1
2
3
4
  if (isNumeric(enteredNumber)) {
      // enteredNumber is numeric, so convert it.
      enteredNumber = Number(enteredNumber);
  }

Check if a value is not a number

1
2
3
4
5
  if (!isNumeric(enteredNumber)) {
      // Input cannot be converted to a number.
      // The not operator, "!", checks for false
      alert("You did not enter a number, please try again.");
  }

New Coding Standard

White space

Notice the white space needed with if statements * Space after the if * Space after the closing parenthesis * Beginning curly brace { on same line as if * Ending curly brace } on it's own line, lined up with

if (condition) {
    ...
}

Demo

  1. Demo: Read Three Characters
    • unit03/demos/demo-three-characters.html

Labs

  1. Lab03: First if
    • unit03/labs/lab-03-first-if.html
  2. Lab04: Simple ifs
    • unit03/labs/lab-04-simpleIfs.html

Exercises

  1. Exercise for lab02
    • unit03/exercises/exercise-02.html
  2. Exercise for lab03
    • unit03/exercises/exercise-03.html