JavaScript Learning Guide – Module 2: Functions
& Scope
1. Declaring and Calling Functions
Functions are reusable blocks of code that perform a specific task. You can declare functions using
the function keyword.
function greet(name) {
return "Hello, " + name + "!";
}
[Link](greet("Alice")); // Output: Hello, Alice!
2. Function Expressions
You can also assign a function to a variable. These are called function expressions.
const greet = function(name) {
return "Hi, " + name;
};
[Link](greet("Bob")); // Output: Hi, Bob
3. Arrow Functions
Arrow functions provide a shorter syntax to write functions, introduced in ES6.
const greet = (name) => "Welcome, " + name;
[Link](greet("Charlie")); // Output: Welcome, Charlie
4. Default Parameters
Functions can have default parameter values if no argument is provided.
function multiply(a, b = 2) {
return a * b;
}
[Link](multiply(5)); // Output: 10
[Link](multiply(5, 3)); // Output: 15
5. Scope: Local vs Global
Scope determines where variables can be accessed. Global variables can be accessed anywhere,
while local variables exist only inside functions or blocks.
let globalVar = "I am global";
function testScope() {
let localVar = "I am local";
[Link](globalVar); // Accessible
[Link](localVar); // Accessible
}
testScope();
[Link](globalVar); // Accessible
// [Link](localVar); // ■ Error: localVar is not defined
■ Mini Task: Age Calculator
Write a function that calculates a user’s age from their birth year.
function calculateAge(birthYear) {
let currentYear = new Date().getFullYear();
return currentYear - birthYear;
}
let year = prompt("Enter your birth year:");
alert("You are " + calculateAge(year) + " years old.");
■ End of Module 2. In the next module, we will learn about Arrays & Objects.