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:
In the code above:
- We first declare a variable
i
and assign it the value5
. - Then, we use an
if
statement to check ifi
is equal to5
. The===
operator is used to check for equality without type coercion. It ensures that both the value and the data type ofi
are equal to5
. - If the condition inside the
if
statement is true (i.e.,i
is equal to 5), the code within the curly braces{ ... }
following theif
statement will be executed. - If the condition is false, the code within the
else
block (if provided) will be executed. In this example, we’ve included anelse
block that logs a message to the console indicating thati
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?
- if i = 5 then
- if i == 5 then
- if i = 5
- 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