Conditional statements allow you to execute different code blocks based on different conditions.
The if statement executes a block of code if the specified
condition is true.
if (condition) {
// Code to execute if condition is true
}
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote!");
}
// Output: "You are eligible to vote!"
The if...else statement executes a block of code if the
condition is true and another block if it's false.
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
let hour = 20;
if (hour < 18) {
console.log("Good day!");
} else {
console.log("Good evening!");
}
// Output: "Good evening!"
The if...else if...else statement checks multiple
conditions in sequence.
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if all conditions are false
}
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else if (score >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}
// Output: "Grade: B"
The ternary operator is a shorthand way to write an
if...else statement in a single line.
condition ? expressionIfTrue : expressionIfFalse;
let age = 20;
let canVote = age >= 18 ? "Yes" : "No";
console.log("Can vote:", canVote); // Output: "Can vote: Yes"
// Equivalent if...else statement:
let canVoteAlt;
if (age >= 18) {
canVoteAlt = "Yes";
} else {
canVoteAlt = "No";
}
Note: Ternary operators can be nested, but this can quickly make code hard to read. Avoid deep nesting!
// Example of hard-to-read nested ternary:
let result = age < 18 ? "Minor" : age < 65 ? "Adult" : "Senior";
The switch statement evaluates an expression and matches it
with case clauses.
switch (expression) {
case value1:
// Code to execute if expression === value1
break;
case value2:
// Code to execute if expression === value2
break;
default:
// Code to execute if no case matches
}
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log("Today is " + dayName); // Output: "Today is Wednesday"
Important: Don't forget the
break statement after each case! Without it, execution
will "fall through" to subsequent cases.
// Intentional fall-through example:
switch (fruit) {
case "apple":
case "pear":
console.log("This is a pome fruit.");
break;
case "orange":
case "lemon":
console.log("This is a citrus fruit.");
break;
}
Returns true if both operands are true.
let hasLicense = true;
let hasInsurance = true;
let canDrive = hasLicense && hasInsurance; // true
// Short-circuit evaluation - the second expression won't be evaluated if the first is false
let result = false && someFunction(); // someFunction() is never called
Returns true if at least one operand is true.
let hasCash = false;
let hasCard = true;
let canPay = hasCash || hasCard; // true
// Short-circuit evaluation - the second expression won't be evaluated if the first is true
let name = userInput || "Guest"; // Default value if userInput is falsy
Returns the opposite of the operand's boolean value.
let isLoggedIn = false;
console.log(!isLoggedIn); // true
// Double NOT (!!) is often used to convert a value to boolean
console.log(!!0); // false
console.log(!!"hello"); // true
Returns the right operand when the left is null or
undefined.
let username = null;
let displayName = username ?? "Guest";
console.log(displayName); // "Guest"
// Different from ||, which returns the right side for any falsy value
let count = 0;
let displayCount = count || "Unknown"; // "Unknown" because 0 is falsy
let actualCount = count ?? "Unknown"; // 0 because it's not null or undefined
Loops allow you to execute code repeatedly until a certain condition is met.
The for loop repeats a block of code a specified number of
times.
for (initialization; condition; increment/decrement) {
// Code to execute in each iteration
}
// Counting from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1 2 3 4 5
// Iterating through an array
const fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Output: Apple Banana Cherry
The while loop executes a block of code as long as the
specified condition is true.
while (condition) {
// Code to execute as long as condition is true
}
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
// Output: 1 2 3 4 5
// Generating a random number until we get one greater than 0.8
let random;
while ((random = Math.random()) <= 0.8) {
console.log("Got:", random);
}
Warning: Be careful with while loops!
Always ensure the condition will eventually become false, or you'll
create an infinite loop.
The do...while loop is similar to the
while loop, but it always executes the code block at least
once before checking the condition.
do {
// Code to execute at least once
} while (condition);
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
// Output: 1 2 3 4 5
// The loop runs once even if the condition is false initially
let j = 10;
do {
console.log("This runs once:", j);
j++;
} while (j <= 5);
// Output: "This runs once: 10"
The for...in loop iterates over all enumerable properties
of an object.
for (variable in object) {
// Code to execute for each property
}
const person = {
name: "John",
age: 30,
city: "New York"
};
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Output:
// name: John
// age: 30
// city: New York
Note: for...in is meant for objects, not
arrays. When used with arrays, it iterates over indices as strings,
not values!
const numbers = [10, 20, 30];
for (let index in numbers) {
console.log(index, typeof index); // "0" string, "1" string, "2" string
console.log(numbers[index]); // 10, 20, 30
}
The for...of loop iterates over iterable objects like
arrays, strings, Maps, etc.
for (variable of iterable) {
// Code to execute for each element
}
const colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
// Output: red green blue
const message = "Hello";
for (let char of message) {
console.log(char);
}
// Output: H e l l o
for...of loop to calculate the total price.
The break statement terminates the current loop or switch
statement.
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break; // Exit the loop when i is 5
}
console.log(i);
}
// Output: 1 2 3 4
The continue statement skips the current iteration and
moves to the next one.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip iteration when i is 3
}
console.log(i);
}
// Output: 1 2 4 5
You can place conditions and loops inside each other to create more complex logic.
// Nested conditions example
let age = 25;
let hasLicense = true;
if (age >= 18) {
if (hasLicense) {
console.log("You can drive a car.");
} else {
console.log("You need a license to drive.");
}
} else {
console.log("You're too young to drive.");
}
// Nested loops example - creating a multiplication table
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`${i} x ${j} = ${i*j}`);
}
console.log('---'); // Separator between rows
}
/* Output:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
---
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
---
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
--- */
Performance Note: Nested loops have O(n²) complexity. Be cautious with large datasets as they can become slow.
const numbers = [12, 5, 8, 130, 44];
let found = false;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > 100) {
console.log("Found number greater than 100:", numbers[i]);
found = true;
break;
}
}
if (!found) {
console.log("No number greater than 100");
}
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = [];
for (let num of numbers) {
if (num % 2 === 0) {
evenNumbers.push(num);
}
}
console.log(evenNumbers); // [2, 4, 6, 8, 10]
let stars = "";
for (let i = 1; i <= 5; i++) {
stars += "*";
console.log(stars);
}
/* Output:
*
**
***
****
***** */
// Example of a do-while to validate user input
function getValidInput() {
let input;
do {
input = prompt("Enter a number between 1 and 100:");
input = Number(input);
} while (isNaN(input) || input < 1 || input > 100);
return input;
}
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}