conditions in JavaScript

testYourself76 1 0

The condition statements in JavaScript is used to execute a block of code only when a certain condition is met. This is the basic control structure that allows decision-making functionality to be added to programs.

If

The if statement executes the statement if the specified condition is true. 

var discount;
if (amount > 10) {
  discount = 0.10;
}

If...else

The if...else statement executes the statement if the specified condition is true. If the condition is false, another statement in the optional else clause will be executed.

var discount;
if (amount > 10) {
  discount = 0.10;
} else {
  discount = 0;
}

if...if else...else

The if...else statement executes the statement if the specified condition is true. If the condition is false, another if statement is checked. If none of the previous if statements are met, the optional else clause will be executed.

var discount;
if (amount > 20) {
  discount = 0.15;
} else if (amount > 10) {
  discount = 0.10;
} else {
  discount = 0;
}

Ternary operator

The ternary operator in JavaScript is a concise way to perform conditional logic. It is called a ternary operator because it uses three operands. The operator can replace simple if...else statements and is often used to assign a value to a variable based on a condition.

var discount = amount > 10 ? 0.10 : 0;