‘If’ Statements in JavaScript

This tutorial explains 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 ented 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 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 evaluates to true (eg. x is less than y), then the code inside 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.

Comparison operators that you can use in JavaScript to make comparisons 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 of if statements below.

Here is the HTML code:

        <title>If statements</title>
        <script src="script.js"></script>


And here is the JavaScript code:

var spend = 100;

if(spend >= 100){
    console.log("You get free shipping!");
else if(spend >= 50){
    console.log("Discounted shipping is $5");
else if(spend >=20){
    console.log("Discounted shipping is $7.50");
    console.log("Shipping is $10");

Next tutorial: Nested if statements

Leave a Reply