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:
- Define and Call basic functions.
- Master Arrow Functions (ES6 syntax).
- Understand Local vs Global Scope.
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.
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.
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
- Create a function
convertToUSD(amount, rate). - It should return the converted value.
- Create another function to display the result in a clean format.
Step-by-Step Process
- Define the conversion logic.
- Call the function with different amounts.
- Log the output: "$[amount] is equal to [value] in USD".
Expected Deliverables
converter.jssource code.