If statements in JavaScript

Coding with JavaScript

🕑 This lesson will take about 10 minutes

In this lesson, you will learn how to use ‘if’ statements for conditional programming in JavaScript. An ‘if’ statement can be used to make decisions based on whether a condition evaluates to true or false. If statements are used to check a condition (for example, if a user’s entered password during login matches their actual password, or if a player’s score is greater than their high score in a game).

‘If’ statements have two parts:

  • the condition being checked which can evaluate to either true or false

  • the instructions in code that will be carried out if the condition evaluates to true

The structure of an ‘if’ statement looks like this:

if(condition to be tested){
  // code to run (if the condition is true) goes here
}

Watch the video below for examples and then scroll down for the sample code.

An ‘if statement’ is used to test a condition. If the test condition (eg. x is less than y) within the parentheses ( ) of the if statement evaluates to true, then the block of code within the curly braces { } of the if statement will run. If the test condition evaluates to false, then the code inside the if statement won’t run and the program will continue on.

Relational operators are used to make comparisons between things. Relational operators that you can use in JavaScript include:

  • Equal to ==

  • Not equal to !=

  • Greater than >

  • Less than <

  • Greater than or equal to >=

  • Less than or equal to <=

Take a look at the sample code for some if statements below.

Sample HTML & JavaScript code

Next tutorial: Nested if statements