In Javascript, the if statement is used for conditional branching, allowing us to execute a block of code if a specified condition evaluates to true.
The `if` condition can be followed by optional `else if` and `else` statements to execute different blocks of code based on different conditions.
if (condition) { // Code to be executed if the condition is true }
let count = 10; // condition statement if `count > 8` then it will print code inside if block if (count > 8) { console.log("count is greater than 8"); }
We can use an "else" block to specify code that should be executed if the condition is false:
let count = 8; // condition statement if `count > 7` then it will print code inside `if` block otherwise `else` block. if (count > 7) { console.log("count is greater than 7"); } else { console.log("count is less than 7"); }
let count = 8; if (count > 10) { console.log("count is greater than 10"); } else if (count >= 5) { console.log("count is equal to 5 or greater than 5 but not greater than 10"); } else { console.log("count is less than 5"); }
We can extend the if-else structure to include multiple conditions using "else if".
let count = 9; let result = (count > 10) ? "count is greater than 10" : "count is not greater than 10"; console.log(result);
The ternary operator (? :) provides a concise way to write simple if-else statements:
let count = 30; if (count > 10) { if (count < 15) { console.log("count is between 10 and 15"); } else { console.log("count is greater than or equal to 15"); } } else { console.log("count is 10 or less"); }
We can nest if statements within each other to create more complex conditional logic: