if in javascript

In JavaScript, the if statement is used to test a condition and execute a block of code if the condition evaluates to true.

The syntax for the if statement is as follows:

index.tsx
if (condition) {
  // code to execute if condition is true
}
61 chars
4 lines

The condition can be any expression that evaluates to a boolean value (true or false). If the condition evaluates to true, the code inside the block will be executed. Otherwise, the code inside the block will be skipped.

Here's an example:

index.tsx
let num = 5;

if (num > 0) {
  console.log("number is positive");
}
68 chars
6 lines

In this example, the condition is num > 0, which evaluates to true since num is 5. Therefore, the code inside the block (i.e., console.log("number is positive")) will be executed and the output will be "number is positive".

You can also use an else statement to execute a block of code if the if statement condition evaluates to false:

index.tsx
let num = -2;

if (num > 0) {
  console.log("number is positive");
} else {
  console.log("number is negative");
}
115 chars
8 lines

In this example, the condition is num > 0, which evaluates to false since num is -2. Therefore, the code inside the else block (i.e., console.log("number is negative")) will be executed and the output will be "number is negative".

gistlibby LogSnag