Sunday, August 17, 2025
0 comments

JavaScript Learning Path: From Zero to Hero – Chapter 3: Control Flow & Functions

 

Introduction

Welcome to Chapter 3 of our JavaScript Learning Path: From Zero to Hero! After mastering variables, data types, and operators in Chapter 2, it’s time to take control of your code’s flow and logic. In this chapter, we’ll explore conditional statements, loops, truthy/falsy values, and functions—the tools that make your programs dynamic and reusable. We’ll build an interactive quiz app to see these concepts in action, with real-world scenarios like scoring answers and managing game flow. Let’s dive in and make your code smarter!


1. Conditional Statements (if, else if, switch)

Conditional statements let your code make decisions based on conditions. JavaScript offers if, else if, else, and switch for branching logic.

If, Else If, Else

The if statement checks a condition and executes code if true. else if and else handle additional cases.

// Real-world example: Movie ticket pricing
function getTicketPrice(age) {
  if (age < 12) {
    return "Child: $5";
  } else if (age < 18) {
    return "Teen: $8";
  } else if (age >= 65) {
    return "Senior: $7";
  } else {
    return "Adult: $10";
  }
}

console.log(getTicketPrice(10)); // Child: $5
console.log(getTicketPrice(16)); // Teen: $8
console.log(getTicketPrice(70)); // Senior: $7
console.log(getTicketPrice(30)); // Adult: $10

Switch Statement

The switch statement is useful for multiple discrete conditions, like selecting a menu option.

function getDayActivity(day) {
  switch (day.toLowerCase()) {
    case "monday":
      return "Work on project";
    case "saturday":
    case "sunday":
      return "Relax and recharge";
    default:
      return "Regular workday";
  }
}

console.log(getDayActivity("Monday")); // Work on project
console.log(getDayActivity("Sunday")); // Relax and recharge
console.log(getDayActivity("Friday")); // Regular workday
  • Pros:

    • if is flexible for complex conditions.

    • switch is cleaner for multiple discrete values.

  • Cons:

    • if chains can become hard to read if too long.

    • switch requires break to avoid fall-through (unless intentional).

  • Best Practices:

    • Use if for range-based or complex conditions.

    • Use switch for fixed-value comparisons.

    • Always include a default case in switch.

  • Alternatives:

    • Object literals for mapping values to outcomes.

    • Ternary operator for simple conditions (covered in Chapter 2).


2. Truthy & Falsy Values

JavaScript evaluates values as truthy or falsy in conditions. Falsy values are:

  • false, 0, -0, 0n, "" (empty string), null, undefined, NaN

All other values are truthy, including "0", [], {}.

Example: Form Validation

function validateInput(input) {
  if (input) {
    return `Input received: ${input}`;
  } else {
    return "Please provide a valid input";
  }
}

console.log(validateInput("Hello")); // Input received: Hello
console.log(validateInput("")); // Please provide a valid input
console.log(validateInput(0)); // Please provide a valid input
console.log(validateInput([])); // Input received: 
  • Real-World Use: Checking if a user entered a name before submitting a form.

  • Pros:

    • Simplifies conditionals (e.g., if (input) instead of if (input !== "")).

  • Cons:

    • Falsy values can lead to unexpected behavior (e.g., 0 is falsy).

  • Best Practices:

    • Use strict equality (===) for specific checks.

    • Be explicit when checking for null or undefined.

  • Alternatives:

    • Explicit checks (e.g., input !== undefined && input !== null).


3. Loops (for, while, do…while)

Loops repeat code until a condition is met. JavaScript offers for, while, and do…while.

For Loop

Great for iterating a known number of times.

// Real-world: Print shopping list items
const shoppingList = ["Milk", "Bread", "Eggs"];
for (let i = 0; i < shoppingList.length; i++) {
  console.log(`Item ${i + 1}: ${shoppingList[i]}`);
}
// Output:
// Item 1: Milk
// Item 2: Bread
// Item 3: Eggs

While Loop

Runs while a condition is true; ideal when the number of iterations is unknown.

// Real-world: Process orders until none remain
let orders = 5;
while (orders > 0) {
  console.log(`Processing order #${orders}`);
  orders--;
}
// Output: Processing order #5, #4, #3, #2, #1

Do…While Loop

Guarantees at least one iteration.

// Real-world: Ask for user input at least once
let attempts = 0;
do {
  attempts++;
  console.log(`Attempt ${attempts}: Checking user login`);
} while (attempts < 3 && Math.random() > 0.5);
// Output: Varies, but runs at least once
  • Pros:

    • for is concise for fixed iterations.

    • while and do…while are flexible for dynamic conditions.

  • Cons:

    • Infinite loops can crash your program.

    • do…while is less commonly used.

  • Best Practices:

    • Use for for arrays or known ranges.

    • Use while for uncertain iterations.

    • Always ensure a loop exit condition.

  • Alternatives:

    • Array methods like forEach, map (covered later).

    • Recursion for complex iterations.


4. Loop Control (break, continue)

break exits a loop; continue skips to the next iteration.

Example: Process Valid Orders

const orders = [100, -50, 200, 0, 300];
for (let i = 0; i < orders.length; i++) {
  if (orders[i] <= 0) {
    console.log(`Skipping invalid order: ${orders[i]}`);
    continue; // Skip negative or zero orders
  }
  if (orders[i] > 250) {
    console.log(`Stopping at large order: ${orders[i]}`);
    break; // Stop if order exceeds $250
  }
  console.log(`Processing order: $${orders[i]}`);
}
// Output:
// Processing order: $100
// Skipping invalid order: -50
// Processing order: $200
// Skipping invalid order: 0
// Stopping at large order: 300
  • Pros:

    • break and continue give fine-grained loop control.

  • Cons:

    • Overuse can make code harder to follow.

  • Best Practices:

    • Use sparingly for clarity.

    • Consider refactoring complex loops into functions.

  • Alternatives:

    • Array methods like filter or some for cleaner logic.


5. Functions

Functions are reusable blocks of code that perform tasks. JavaScript offers multiple ways to define them.

Function Declaration

function greet(name) {
  return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Hello, Alice!

Function Expression

const multiply = function(a, b) {
  return a * b;
};
console.log(multiply(4, 5)); // 20

Arrow Functions

Introduced in ES6, concise and don’t bind their own this.

const add = (a, b) => a + b;
console.log(add(3, 7)); // 10

Parameters, Return Values, Default Parameters

function calculateDiscount(price, discount = 0.1) {
  return price * (1 - discount);
}
console.log(calculateDiscount(100)); // 90 (uses default 10%)
console.log(calculateDiscount(100, 0.2)); // 80 (20% discount)
  • Pros:

    • Declarations are hoisted, usable anywhere in scope.

    • Arrow functions are concise for simple operations.

    • Default parameters simplify function calls.

  • Cons:

    • Arrow functions can’t be used as constructors or with this.

    • Function expressions aren’t hoisted.

  • Best Practices:

    • Use declarations for top-level functions, expressions for callbacks.

    • Keep functions single-purpose and short.

    • Use default parameters for optional inputs.

  • Alternatives:

    • Class methods for object-oriented programming.

    • Immediately Invoked Function Expressions (IIFEs) for one-time execution.


6. Scope (Local, Block, Global)

Scope determines where variables are accessible:

  • Global: Outside functions, accessible everywhere.

  • Local: Inside functions, only accessible there.

  • Block: Inside {} (with let/const), e.g., loops or conditionals.

Example: Budget Tracker

const globalBudget = 1000; // Global scope
function trackSpending(amount) {
  let remaining = globalBudget - amount; // Local scope
  if (remaining > 0) {
    let message = "Funds available"; // Block scope
    console.log(message);
  }
  // console.log(message); // Error: message is not defined
  return remaining;
}
console.log(trackSpending(200)); // Funds available, 800
console.log(globalBudget); // 1000
  • Pros:

    • Block scope (let, const) prevents variable leaks.

    • Local scope protects variables from unintended changes.

  • Cons:

    • Global variables can cause naming conflicts.

    • Misunderstanding scope leads to bugs.

  • Best Practices:

    • Minimize global variables.

    • Use let or const for block-scoped variables.

    • Avoid implicit globals (e.g., omitting let/const).


7. Higher-Order Functions

A higher-order function takes a function as an argument or returns a function.

-ice: A timer function for example.

function timer(callback) {
  setTimeout(callback, 1000);
}

timer(() => console.log("Time's up!")); // Time's up! (after 1 second)

Real-World Example: Filter Valid Scores

const scores = [85, -10, 90, 0, 95];
const filterPositive = (arr, condition) => arr.filter(condition);
const positiveScores = filterPositive(scores, score => score > 0);
console.log(positiveScores); // [85, 90, 95]
  • Pros:

    • Enables functional programming patterns.

    • Reusable and modular code.

  • Cons:

    • Can be complex for beginners.

    • Callback-heavy code can lead to “callback hell.”

  • Best Practices:

    • Use clear, descriptive callback names.

    • Prefer arrow functions for concise callbacks.

  • Alternatives:

    • Promises or async/await for asynchronous tasks.


Interactive Example: Quiz App

Let’s combine everything into a quiz app that scores user answers.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Quiz App</title>
  <style>
    body { font-family: Arial, sans-serif; padding: 20px; }
    .question { margin-bottom: 20px; }
    button { padding: 10px; background: #4CAF50; color: white; border: none; cursor: pointer; }
    #result { color: green; font-weight: bold; }
  </style>
</head>
<body>
  <h2>Quick Quiz</h2>
  <div class="question">
    <p>1. What is 2 + 2?</p>
    <input type="text" id="q1" placeholder="Your answer">
  </div>
  <div class="question">
    <p>2. Is JavaScript case-sensitive?</p>
    <input type="text" id="q2" placeholder="Yes/No">
  </div>
  <button onclick="submitQuiz()">Submit Quiz</button>
  <p id="result"></p>
  <script>
    function submitQuiz() {
      const q1 = document.getElementById('q1').value;
      const q2 = document.getElementById('q2').value.toLowerCase();
      let score = 0;

      // Question 1: Arithmetic and conditional
      if (Number(q1) === 4) {
        score++;
      }

      // Question 2: Truthy/falsy and switch
      switch (q2) {
        case "yes":
          score++;
          break;
        case "no":
          break;
        default:
          console.log("Invalid input for Q2");
      }

      // Higher-order function for result
      const displayResult = (points, callback) => {
        const message = callback(points);
        document.getElementById('result').textContent = message;
      };

      displayResult(score, points => `You scored ${points}/2!`);
    }
  </script>
</body>
</html>
  • How It Works:

    • Uses conditionals to check answers.

    • Employs a switch for discrete input validation.

    • Demonstrates a higher-order function for result display.

    • Handles user input with truthy/falsy checks.

  • Why It’s Useful: Mimics real quiz apps used in education or trivia games.


Best Standards for Control Flow & Functions

  • Conditionals: Keep if chains short; use objects or switch for clarity.

  • Loops: Ensure clear exit conditions to avoid infinite loops.

  • Functions: Write single-purpose, reusable functions.

  • Scope: Prefer block scope (let, const) over global variables.

  • Documentation: Use JSDoc for complex functions.


Conclusion

You’ve just conquered control flow and functions in JavaScript! From conditionals and loops to arrow functions and higher-order functions, you’re now equipped to create dynamic, reusable code. The quiz app demonstrates how these concepts power real-world applications.

What’s Next? In Chapter 4, we’ll dive into arrays, objects, and methods, building a task management app to organize your projects. Keep coding, and try adding a third question to the quiz app for practice!

Interactive Challenge: Enhance the quiz app to loop through multiple questions stored in an array and calculate a percentage score. Share your solution with #JavaScriptHero!

0 comments:

Featured Post

Master Angular 20 Basics: A Complete Beginner’s Guide with Examples and Best Practices

Welcome to the complete Angular 20 learning roadmap ! This series takes you step by step from basics to intermediate concepts , with hands...

Subscribe

 
Toggle Footer
Top