In JavaScript, you can use the if
statement to execute a block of code if a condition is true
. The syntax for the if
statement is as follows:
if (condition) { // code to execute if the condition is true }
In this example, condition
is a boolean expression that is evaluated to either true
or false
. If the condition is true
, the code inside the curly braces is executed. If the condition is false
, the code is skipped and execution continues with the next statement after the if
block.
Here is an example of how to use the if
statement to check if a number is positive:
var number = 10; if (number > 0) { console.log("The number is positive."); }
In this example, the condition number > 0
is evaluated to true
, so the code inside the curly braces is executed and the message "The number is positive." is printed to the console.
You can also use the if-else
statement to execute different blocks of code based on a condition. The syntax for the if-else
statement is as follows:
if (condition) { // code to execute if the condition is true } else { // code to execute if the condition is false }
Here is an example of how to use the if-else
statement to check if a number is positive or negative:
var number = 10; if (number > 0) { console.log("The number is positive."); } else { console.log("The number is negative."); }
In this example, the condition number > 0
is evaluated to true
, so the code inside the first set of curly braces is executed and the message "The number is positive." is printed to the console.
Note that the if
and if-else
statements are powerful tools for controlling the flow of your program based on different conditions. It is important to carefully consider the conditions and actions in your if
and if-else
statements to ensure that your code is correct and easy to understand.