JavaScript Notes: Conditionals
JavaScript Conditionals
Conditionals in JavaScript allow you to make decisions in your code based on certain conditions. They are used to execute different code blocks depending on whether a given condition evaluates to true or false.
If Statement:
The if
statement is the simplest conditional statement. It executes a code block only if the specified condition is true:
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
If-Else Statement:
The if-else
statement adds an alternative code block to execute when the condition is false:
let hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else {
console.log("Good afternoon!");
}
Else-If Statement:
The else if
statement allows you to add multiple conditions to check:
let score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("D");
}
Ternary Operator:
The ternary operator offers a concise way to create conditional expressions:
let isStudent = true;
let status = (isStudent) ? "Student" : "Not a student";
console.log(status);
Switch Statement:
The switch
statement is used for multiple branches based on the value of an expression:
let day = "Wednesday";
switch (day) {
case "Monday":
console.log("It's the start of the week.");
break;
case "Friday":
console.log("It's the end of the week.");
break;
default:
console.log("It's a regular day.");
}
break
in a case makes only that case’s code run. Without break
, if a case matches, the following case’s code will also run. This is called “fall through” and can be helpful sometimes. An example is as follows:
let dayOfWeek = 3; // Wednesday
switch (dayOfWeek) {
case 1:
console.log("It's Monday.");
break;
case 2:
case 3:
case 4:
case 5:
console.log("It's a weekday.");
break;
case 6:
console.log("It's Saturday.");
break;
case 7:
console.log("It's Sunday.");
break;
default:
console.log("Invalid day.");
}
}
It’s worth noting that the switch
statement can also be used without an expression, like this:
let fruit = “banana”; switch(true) { case fruit === “apple”: console.log(“This is an apple”); break; case fruit === “banana”: console.log(“This is a banana”); break; default: console.log(“I don’t know what fruit this is”); break; }
In this example, the switch statement doesn’t have an expression; instead, each case statement is a boolean expression that evaluates to true or false.
The switch statement checks each case expression in turn until it finds one that evaluates to true, and then executes the associated code block.
Conditionals are a fundamental part of programming, enabling you to create dynamic and responsive code that adapts to different scenarios.