🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

If else conditionals

JavaScript Conditional Statements: if, else if, else

JavaScript Conditional Statements: if, else if, else

if Statement:

The if statement is used to execute a block of code if a specified condition evaluates to true.

let x = 10;

if (x > 5) {
  console.log("x is greater than 5");
}

if-else Statement:

The if-else statement allows you to execute one block of code if a condition is true and another block if the condition is false.

let y = 3;

if (y > 5) {
  console.log("y is greater than 5");
} else {
  console.log("y is not greater than 5");
}

else if Statement:

The else if statement allows you to check additional conditions if the preceding if or else if conditions are false.

let z = 7;

if (z > 10) {
  console.log("z is greater than 10");
} else if (z > 5) {
  console.log("z is greater than 5 but not greater than 10");
} else {
  console.log("z is 5 or less");
}

Nesting Conditionals:

You can also nest if statements within each other to create more complex conditional structures.

let a = 15;

if (a > 10) {
  if (a < 20) {
    console.log("a is between 10 and 20");
  } else {
    console.log("a is greater than or equal to 20");
  }
} else {
  console.log("a is 10 or less");
}

Ternary Operator (Conditional Operator):

The ternary operator is a shorthand way of writing a simple if-else statement.

let b = 8;

let result = (b > 5) ? "b is greater than 5" : "b is 5 or less";

console.log(result);

Truthy and Falsy Values:

Keep in mind that JavaScript has truthy and falsy values. In conditional statements, values are coerced to a boolean (true or false). Falsy values include false, 0, '' (empty string), null, undefined, and NaN. Any other value is considered truthy.

let value = 0;

if (value) {
  console.log("Truthy");
} else {
  console.log("Falsy");
}

Understanding conditional statements is crucial for controlling the logical flow of your programs and making decisions based on various conditions.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.