In JavaScript, an if statement is a conditional statement that is used to execute a block of code only if a specified condition is true. If the condition is false, the code in the if statement will not be executed.
Here is an example of an if statement in JavaScript:
// Define a variable and assign a value
var score = 80;
// Check if the value of the variable is greater than or equal to 60
if (score >= 60) {
// If the condition is true, execute this code
console.log('The score is passing');
}
In this example, we are defining a variable and assigning it a value. We are then using an if statement to check if the value of the variable is greater than or equal to 60. If the condition is true, the code in the if statement is executed and a message is logged to the console. If the condition is false, the code in the if statement is not executed.
We can also use an else statement with an if statement to specify code that should be executed if the condition in the if statement is false. Here is an example of using an else statement with an if statement in JavaScript:
// Define a variable and assign a value
var score = 40;
// Check if the value of the variable is greater than or equal to 60
if (score >= 60) {
// If the condition is true, execute this code
console.log('The score is passing');
} else {
// If the condition is false, execute this code
console.log('The score is failing');
}
In this example, we are using an if statement and an else statement to check if the value of the variable is greater than or equal to 60. If the condition is true, the code in the if statement is executed and a message is logged to the console.
If the condition is false, the code in the else statement is executed and a different message is logged to the console. This allows us to specify different code to be executed depending on whether the condition in the if statement is true or false.
I hope you find this useful. Please comment if you have any questions.