šŸ 

šŸŽ“ Conditions and Loops in JavaScript

🌟 Objective: Master Conditional Statements and Loops for Program Flow Control in JavaScript!

šŸ“‘ Table of Contents

šŸ”€ Conditional Statements

Conditional statements allow you to execute different code blocks based on different conditions.

🚦 if Statement

The if statement executes a block of code if the specified condition is true.

if (condition) {
 // Code to execute if condition is true
}
Example:
let age = 18;
if (age >= 18) {
 console.log("You are eligible to vote!");
}
// Output: "You are eligible to vote!"

šŸ”„ if...else Statement

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
}
Example:
let hour = 20;
if (hour < 18) {
 console.log("Good day!");
} else {
 console.log("Good evening!");
}
// Output: "Good evening!"

🌈 if...else if...else Statement

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
}
Example:
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"
šŸ’” Real-world Example:
Determining shipping costs based on the order value. Different price ranges get different shipping rates.

šŸ”® Ternary Operator

The ternary operator is a shorthand way to write an if...else statement in a single line.

condition ? expressionIfTrue : expressionIfFalse;
Example:
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";

šŸ”„ switch Statement

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
}
Example:
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;
}

🧠 Logical Operators

šŸ”— AND Operator (&&)

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

šŸ”€ OR Operator (||)

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

ā— NOT Operator (!)

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

šŸ” Nullish Coalescing (??)

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

šŸ”„ Loop Structures

Loops allow you to execute code repeatedly until a certain condition is met.

šŸ“‹ for Loop

The for loop repeats a block of code a specified number of times.

for (initialization; condition; increment/decrement) {
 // Code to execute in each iteration
}
Example:
// 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

šŸ”„ while Loop

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
}
Example:
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.

šŸ” do...while 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);
Example:
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"

šŸ” for...in Loop

The for...in loop iterates over all enumerable properties of an object.

for (variable in object) {
 // Code to execute for each property
}
Example:
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
}

šŸ“¦ for...of Loop

The for...of loop iterates over iterable objects like arrays, strings, Maps, etc.

for (variable of iterable) {
 // Code to execute for each element
}
Example:
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
šŸ’” Real-world Example:
Processing items in a shopping cart array using a for...of loop to calculate the total price.

šŸ›‘ Loop Control Statements

🚪 break Statement

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

ā­ļø continue Statement

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

🧩 Nested Conditions and Loops

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.

šŸ” Common Patterns and Use Cases

Finding Elements in an Array

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");
}

Filtering Elements

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]

Building a String with a Loop

let stars = "";
for (let i = 1; i <= 5; i++) {
 stars += "*";
 console.log(stars);
}
/* Output:
*
**
***
****
***** */

Input Validation Loop

// 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;
}

šŸ’Ŗ Practice Exercises

  1. FizzBuzz: Write a program that prints numbers from 1 to 100. For multiples of 3, print "Fizz" instead of the number. For multiples of 5, print "Buzz". For multiples of both 3 and 5, print "FizzBuzz".
  2. Sum of Even Numbers: Calculate the sum of all even numbers from 1 to 100.
  3. Nested Loops Pattern: Print a pattern of asterisks forming a right-angled triangle.
  4. Find Prime Numbers: Write a program that finds all prime numbers between 1 and 50.
  5. Temperature Converter: Create a program that converts temperatures between Celsius and Fahrenheit based on user input.

Exercise Solution Example: FizzBuzz

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);
 }
}