# Native JavaScript - Conditional Statements and Loops

## If and Else in JavaScript

**If** and **else** statements in JavaScript are fundamental control structures used to execute different blocks of code based on whether a condition evaluates to true or false.

### **The if Statement**

* The `if` statement checks a condition (an expression that returns true or false).
* If the condition is true, the code inside the `if` block runs.
* If the condition is false, the code inside the `if` block is skipped.

**Syntax:**

```javascript
if (condition) {
  // Code to execute if condition is true
}
```

**Example:**

```javascript
let age = 19;
if (age > 18) {
  console.log("Congratulations, You are eligible to drive");
}
// Output: Congratulations, You are eligible to drive
```

### **The if...else Statement**

* The `else` statement can be paired with `if` to specify code that runs if the condition is false.

**Syntax:**

```javascript
if (condition) {
  // Code if condition is true
} else {
  // Code if condition is false
}
```

**Example:**

```javascript
let i = 10;
if (i < 15) {
  console.log("i is less than 15");
} else {
  console.log("I am Not in if");
}
// Output: i is less than 15
```

### **The else if Statement**

* Use `else if` to test multiple conditions in sequence.
* JavaScript evaluates each condition in order; the first true condition's block runs, and the rest are skipped.

**Syntax:**

```javascript
if (condition1) {
  // Code if condition1 is true
} else if (condition2) {
  // Code if condition2 is true
} else {
  // Code if none of the above conditions are true
}
```

**Example:**

```javascript
var age = 27;
if (age <= 10) {
  ticketPrice = 5;
} else if (age >= 11 && age <= 17) {
  ticketPrice = 8;
} else if (age >= 18 && age <= 64) {
  ticketPrice = 12;
} else {
  ticketPrice = 8;
}
console.log(ticketPrice); // Output: 12
```

### **Summary Table**

| Statement | Purpose                                            | Example Condition   |
| --------- | -------------------------------------------------- | ------------------- |
| if        | Executes block if condition is true                | `if (x > 5)`        |
| else      | Executes block if previous `if`/`else if` is false | `else { ... }`      |
| else if   | Tests a new condition if previous is false         | `else if (x === 0)` |

**In summary:**

* Use `if` to check a condition.
* Use `else` to handle the opposite case.
* Use `else if` to check additional conditions in sequence.\
  These statements are essential for decision-making in JavaScript programs

## Switch Case in JavaScript

The **switch** statement in JavaScript is a control structure used to execute different blocks of code based on the value of an expression. It is often used as a cleaner alternative to multiple `if...else if...else` statements when you need to compare a single value against several possible matches

### **Syntax**

```javascript
switch (expression) {
  case value1:
    // Code to execute if expression === value1
    break;
  case value2:
    // Code to execute if expression === value2
    break;
  // More cases as needed
  default:
    // Code to execute if no case matches
}
```

* The `expression` is evaluated once.
* The result is compared using **strict equality (`===`)** to each `case` value in order.
* If a match is found, the corresponding block runs.
* The `break` statement exits the switch block; otherwise, execution "falls through" to the next case.
* If no case matches, the `default` block (if present) runs

### **Example**

```javascript
let dayNumber = new Date().getDay();
let dayName;

switch (dayNumber) {
  case 0:
    dayName = "Sunday";
    break;
  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;
  default:
    dayName = "Unknown day";
}
console.log(dayName);
```

This code assigns the current weekday name to `dayName`

### **Key Points**

* **Strict Comparison:** Case values are compared with the expression using `===`. Type must match for a case to be selected
* **Break Statement:** Prevents code from running into the next case. If omitted, execution continues ("falls through") to the next case
* **Default Case:** Runs if no case matches. It's optional and can appear anywhere in the switch block, but usually comes last
*   **Grouped Cases:** Multiple cases can share the same code block by omitting `break` between them:

    ```javascript
    switch (value) {
      case 1:
      case 2:
        // Code for both 1 and 2
        break;
      default:
        // Default code
    }
    ```

    This executes the same code for both case 1 and case 2

### **When to Use switch**

* When you need to compare a single variable or expression to several possible values.
* When you want cleaner, more readable code than multiple `if...else if` statements

**In summary:**\
The `switch` statement is a powerful tool for multi-way branching based on the value of a single expression, offering better readability and maintainability for such scenarios in JavaScript

## For Loop in JavaScript

The **for loop** in JavaScript is a fundamental control structure used to repeat a block of code a specific number of times. It's commonly used for tasks like iterating over arrays, counting, or performing repetitive actions.

### **Syntax**

```javascript
for (initialExpression; condition; updateExpression) {
  // Code block to execute
}
```

* **initialExpression**: Initializes a counter variable (runs once before the loop starts).
* **condition**: The loop continues as long as this evaluates to `true` (checked before each iteration).
* **updateExpression**: Updates the counter variable (runs after each iteration)[2](https://www.programiz.com/javascript/for-loop)[5](https://www.w3schools.com/js/js_loop_for.asp)[3](https://www.javascripttutorial.net/javascript-for-loop/).

### **Basic Example**

```javascript
for (let i = 0; i < 3; i++) {
  console.log("Hello, world!");
}
// Output:
// Hello, world!
// Hello, world!
// Hello, world!
```

This prints "Hello, world!" three times because the loop runs while `i` is less than 3

### **How It Works**

1. **Initialization**: Set up a variable (e.g., `let i = 0`).
2. **Condition Check**: If the condition (e.g., `i < 3`) is true, execute the loop body.
3. **Execution**: Run the code inside the loop.
4. **Update**: Increase (or otherwise update) the variable (e.g., `i++`).
5. **Repeat**: Go back to step 2. Stop when the condition is false

### **Iterating Over Arrays**

For loops are often used to process each element of an array:

```javascript
let fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// Output:
// Apple
// Banana
// Cherry
```

This loop prints each fruit in the array

### **Omitting Expressions**

All three expressions are optional:

* You can omit the initializer if the variable is already declared.
* You can omit the update if you update the variable inside the loop.
* Omitting the condition creates an infinite loop (not recommended)

Example without initializer:

```javascript
let j = 1;
for (; j < 10; j += 2) {
  console.log(j);
}
// Output: 1, 3, 5, 7, 9
```

### **Looping in Reverse**

You can count downwards by adjusting the initialization, condition, and update:

```javascript
for (let i = 10; i > 0; i--) {
  console.log(i);
}
// Output: 10, 9, ..., 1
```

### **Summary Table**

| Part           | Purpose                         | Example     |
| -------------- | ------------------------------- | ----------- |
| Initialization | Set starting value              | `let i = 0` |
| Condition      | Loop continues while true       | `i < 5`     |
| Update         | Change variable after each loop | `i++`       |

### While Loop in JavaScript

A **while loop** in JavaScript repeatedly executes a block of code as long as a specified condition evaluates to `true`. It is especially useful when you do not know beforehand how many times you need to repeat an action—the loop continues until the condition becomes false

### **Syntax**

```javascript
while (condition) {
  // code block to be executed
}
```

* The `condition` is evaluated before each iteration.
* If the condition is `true`, the code block runs.
* After the code block executes, the condition is checked again.
* The loop ends when the condition is `false`

### **Example**

```javascript
let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}
// Output: 0 1 2 3 4
```

In this example, the loop prints numbers from 0 to 4. The variable `i` is incremented on each iteration, and the loop stops when `i` reaches 5

### **Key Points**

* **Pre-check Loop:** The condition is checked before the code block runs. If the condition is `false` initially, the loop body may not execute at all
* **Infinite Loop Risk:** If you forget to update the variable in the condition (e.g., `i++`), the loop may never end, causing your program to hang
* **Use Cases:** While loops are ideal when the number of iterations is not known in advance, such as waiting for a user action or an external event

## **do...while Loop**

A related construct is the **do...while loop**, which always executes the code block at least once before checking the condition:

```javascript
let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);
```

This will print numbers 0 to 4, just like the previous example, but the loop body is guaranteed to run at least once[1](https://www.w3schools.com/js/js_loop_while.asp)[5](https://www.programiz.com/javascript/while-loop).

### **Summary Table**

| Loop Type  | Condition Checked | Minimum Executions | Use Case                      |
| ---------- | ----------------- | ------------------ | ----------------------------- |
| while      | Before loop body  | 0                  | Unknown number of repetitions |
| do...while | After loop body   | 1                  | At least one execution needed |

**In summary:**\
The `while` loop in JavaScript is a control structure that repeats code as long as a condition is true, making it well-suited for tasks where the number of iterations is not predetermined



***

Answer from Perplexity: [pplx.ai/share](https://www.perplexity.ai/search/pplx.ai/share)
