How to use if statement in JavaScript ?

An if statement in JavaScript is used for conditional execution. It evaluates a condition inside parentheses and executes a block of code if the condition is true. The if statement is one of the fundamental building blocks in programming, enabling developers to create dynamic and responsive applications.

By using if statements, you can control the flow of your program and make decisions based on various conditions. This allows for more complex logic and interactive features, making your code more versatile and powerful. Whether you’re validating user input, handling errors, or managing application states, mastering if statements is essential for any JavaScript developer.

Example: Here, the if statement checks whether the variable num is greater than 0. If the condition num > 0 evaluates to true, the code block inside the curly braces (console.log("Number is positive.")) is executed, and it prints “Number is positive.” to the console.

Javascript
let num = 10;

if (num  > 0) {
    console.log("Number is positive.");
}

Output
Number is positive.

Contact Us