Chapter 4 — JS Functions & Scope

📚 Chapter Overview

Don't repeat yourself (DRY). In this chapter, you will learn how to wrap logic into reusable Functions, pass data using Parameters, and understand where variables live using Scope.

Learning Objectives:

4.1 Function Basics

Part 1 — Definition

A Function is a block of code designed to perform a particular task. It is executed when "something" invokes it (calls it). Functions allow you to reuse code: Define the code once, and use it many times.

Part 2 — Syntax

function sayHello(name) {
    console.log("Hello " + name);
}

// Call
sayHello("Alice");

Part 3 — Example

Problem: Create a function that adds two numbers and returns the result.

script.js
function add(a, b) {
    return a + b;
}

let result = add(5, 10);
console.log(result); // 15

Part 4 — Video

Video: Coming Soon


4.2 Arrow Functions & Scope

Part 1 — Definition

Arrow Functions are a shorter syntax for writing functions, introduced in ES6. Scope determines the accessibility of variables. Variables defined inside a function are "Local" and cannot be accessed from outside.

Part 2 — Syntax

const greet = () => console.log("Hi");
let globalVar = "I am everywhere";

Part 3 — Example

Problem: Demonstrate local scope vs global scope.

script.js
let name = "Global";

function testScope() {
    let name = "Local";
    console.log(name); // Prints "Local"
}

testScope();
console.log(name); // Prints "Global"

Part 4 — Video

Video: Coming Soon


🏆 Chapter Challenge

Challenge Objective

Build a "Mini Currency Converter" using functions.

Requirements

Step-by-Step Process

  1. Define the conversion logic.
  2. Call the function with different amounts.
  3. Log the output: "$[amount] is equal to [value] in USD".

Expected Deliverables

Solve in Editor