In JavaScript, the if statement is used for branching – allowing you to execute a block of code only if a specified condition is true. Here is the basic syntax of an if statement in JavaScript:
index.tsx69 chars4 lines
The condition is a statement that evaluates to either true or false. If it evaluates to true, then the code within the curly braces will be executed. If it evaluates to false, then the code within the curly braces will be skipped.
Here's an example of using an if statement to check if a number is greater than 5:
index.tsx85 chars6 lines
In this example, the condition is number > 5, which evaluates to true because number is 10. Therefore, the code within the curly braces will be executed, and the message "The number is greater than 5" will be printed to the console.
You can also use an else statement to specify what should happen if the condition is false. Here's an example:
index.tsx149 chars8 lines
In this example, the condition is number > 5, which evaluates to false because number is 2. Therefore, the code within the else block will be executed, and the message "The number is less than or equal to 5" will be printed to the console.
gistlibby LogSnag