Class 6: JavaScript Fundamentals: Loops, conditionals, and arrays.

JavaScript is one of the most widely used programming languages for web development. In this class, we will discuss three essential concepts: LoopsConditionals, and Arrays. These are foundational tools for controlling the flow of a program, handling repetitive tasks, and managing collections of data.

1. Loops in JavaScript

Loops are used to execute a block of code repeatedly until a specified condition is met. They are powerful tools for iterating over data structures or performing repetitive actions.

Types of Loops in JavaScript

  1. for loop
    A loop that runs for a specific number of iterations.for (let i = 0; i < 5; i++) { console.log("Iteration number: " + i); } Explanation:

    • let i = 0 initializes the loop variable i.
    • i < 5 is the condition that must be true for the loop to continue.
    • i++ increments the value of i after each iteration.
  2. while loop
    A loop that runs as long as a condition is true.let i = 0; while (i < 5) { console.log("While loop iteration: " + i); i++; } Explanation:

    • The loop checks the condition i < 5 before executing the code block.
    • The i++ increments the value of i after each iteration.
  3. do...while loop
    Similar to the while loop, but it executes the code block at least once before checking the condition.let i = 0; do { console.log("Do-while loop iteration: " + i); i++; } while (i < 5);

4. for...of loop
Used to iterate over iterable objects like arrays, strings, etc.

const fruits = ["apple", "banana", "cherry"];  
for (const fruit of fruits) {  
    console.log(fruit);  
}  

5. for...in loop
Used to iterate over the properties of an object.

const person = { name: "John", age: 30, city: "New York" };  
for (const key in person) {  
    console.log(key + ": " + person[key]);  
}  

2. Conditionals in JavaScript

Conditionals allow you to execute different blocks of code based on certain conditions.

Types of Conditionals

  1. if Statementlet age = 18; if (age >= 18) { console.log("You are eligible to vote."); } Explanation:
    The code inside the if block will run only if the condition age >= 18 is true.
  2. if...else Statementlet age = 16; if (age >= 18) { console.log("You are eligible to vote."); } else { console.log("You are not eligible to vote."); }

3. else if Statement

let score = 85;  
if (score >= 90) {  
    console.log("Grade: A");  
} else if (score >= 80) {  
    console.log("Grade: B");  
} else {  
    console.log("Grade: C");  
}  

4. switch Statement
The switch statement is used to perform different actions based on different conditions.

let day = 3;  
switch (day) {  
    case 1:  
        console.log("Monday");  
        break;  
    case 2:  
        console.log("Tuesday");  
        break;  
    case 3:  
        console.log("Wednesday");  
        break;  
    default:  
        console.log("Invalid day");  
}  

3. Arrays in JavaScript

An array is a collection of elements that can be of any data type. Arrays allow you to store multiple values in a single variable.

Creating an Array

const numbers = [1, 2, 3, 4, 5];  
const fruits = ["apple", "banana", "cherry"];  

Accessing Array Elements

You can access array elements using their index (starting from 0).

console.log(fruits[0]); // Output: apple  
console.log(fruits[1]); // Output: banana  

Common Array Methods

  1. push() – Adds an element to the end of the array.fruits.push("date"); console.log(fruits); // ["apple", "banana", "cherry", "date"]

2. pop() – Removes the last element from the array.

fruits.pop();  
console.log(fruits); // ["apple", "banana", "cherry"]  

3. shift() – Removes the first element from the array.

fruits.shift();  
console.log(fruits); // ["banana", "cherry"]  

4. unshift() – Adds an element to the beginning of the array.

fruits.unshift("apricot");  
console.log(fruits); // ["apricot", "banana", "cherry"]  

5. length – Returns the number of elements in the array.

console.log(fruits.length); // 3  

6. splice() – Adds or removes elements from the array.

fruits.splice(1, 1, "blueberry");  
console.log(fruits); // ["apricot", "blueberry", "cherry"]  

7. slice() – Returns a shallow copy of a portion of the array.

const newFruits = fruits.slice(1, 3);  
console.log(newFruits); // ["blueberry", "cherry"]  

8. forEach() – Executes a provided function once for each array element.

fruits.forEach(fruit => console.log(fruit));  

9. map() – Creates a new array with the results of calling a function on every element.

const upperFruits = fruits.map(fruit => fruit.toUpperCase());  
console.log(upperFruits); // ["APRICOT", "BLUEBERRY", "CHERRY"]  

10. filter() – Creates a new array with elements that pass a test.
javascript const longFruits = fruits.filter(fruit => fruit.length > 6); console.log(longFruits); // ["blueberry"]

Putting It All Together – Example

Here’s a practical example that combines loops, conditionals, and arrays:

const students = [  
    { name: "Alice", score: 85 },  
    { name: "Bob", score: 72 },  
    { name: "Charlie", score: 90 },  
    { name: "Dave", score: 65 }  
];  
  
// Loop through the students array  
for (const student of students) {  
    // Use a conditional to determine the grade  
    let grade;  
    if (student.score >= 90) {  
        grade = "A";  
    } else if (student.score >= 80) {  
        grade = "B";  
    } else if (student.score >= 70) {  
        grade = "C";  
    } else {  
        grade = "D";  
    }  
    console.log(`${student.name} scored ${student.score} and got a grade of ${grade}.`);  
}  

Output:

Alice scored 85 and got a grade of B.  
Bob scored 72 and got a grade of C.  
Charlie scored 90 and got a grade of A.  
Dave scored 65 and got a grade of D.  

Key Takeaways

  1. Loops automate repetitive tasks. Use forwhiledo...whilefor...of, and for...in depending on the use case.
  2. Conditionals allow you to control the flow of the program. Use ifif...elseelse if, and switch for decision-making.
  3. Arrays store and manipulate collections of data. Learn common methods like pushpopmapfilter, and forEach.

    By mastering these three concepts, you’ll have a solid foundation to tackle complex JavaScript problems.