Skip to content

How to write an if statement in JavaScript if i=5 | Example code

  • by

JavaScript if Conditional statements are used to decide the flow of execution based on conditions. If a condition is true, you can perform one action and if the condition is false, you can perform another action.

if (condition){
    //lines of code to be executed if condition is true
}

How to write an if statement in JavaScript if i=5

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    var i = 5;

    if (i = 5) {
      console.log("The number is", 5);
    }
    else {
      console.log("The number is not 5");
    }

  </script>
</body>
</html> 

Output:

How to write an if statement in JavaScript if i 5

In the code above:

  1. We first declare a variable i and assign it the value 5.
  2. Then, we use an if statement to check if i is equal to 5. The === operator is used to check for equality without type coercion. It ensures that both the value and the data type of i are equal to 5.
  3. If the condition inside the if statement is true (i.e., i is equal to 5), the code within the curly braces { ... } following the if statement will be executed.
  4. If the condition is false, the code within the else block (if provided) will be executed. In this example, we’ve included an else block that logs a message to the console indicating that i is not equal to 5.

So, if you run this code with i equal to 5, you will see the message “i is equal to 5” logged to the console. If i is any other value, you will see the “i is not equal to 5” message.

How to write an IF statement in JavaScript?

  1. if i = 5 then
  2. if i == 5 then
  3. if i = 5
  4. if (i == 5)

ANSWER: D

Not equal to in JavaScript if statement

Since a is not equal to 5, it will print true.

let a = 12

if(a!=5){
  console.log(true)
}

Output: true

Do comment if you have any doubts or suggestions on this JS if statement.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading