if statement in javascript

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.tsx
if (condition) {
  // code to be executed if the condition is true
}
69 chars
4 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.tsx
let number = 10;

if (number > 5) {
  console.log("The number is greater than 5");
}
85 chars
6 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.tsx
let number = 2;

if (number > 5) {
  console.log("The number is greater than 5");
} else {
  console.log("The number is less than or equal to 5");
}
149 chars
8 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