Course Lessons
Lesson 2 of 3
Functions and Scope
Master JavaScript functions including declarations, expressions, arrow functions, and understand how scope works.
24 minutes
Functions and Scope
Functions are reusable blocks of code that perform specific tasks.
Function Declarations
The traditional way to define a function:
function greet(name) {
return `Hello, ${name}!`;
}
Arrow Functions
Modern ES6 syntax for shorter function expressions:
const greet = (name) => `Hello, ${name}!`;
Understanding Scope
- Global Scope: Variables accessible everywhere
- Function Scope: Variables only accessible within the function
- Block Scope: Variables only accessible within
{}blocks
Key Takeaway
Arrow functions are great for callbacks and short functions, while traditional functions are better when you need the this keyword.
Code Example
// Function declaration
function add(a, b) {
return a + b;
}
// Arrow function
const multiply = (a, b) => a * b;
// Function with default parameters
const greet = (name = "Guest") => {
return `Welcome, ${name}!`;
};
console.log(add(5, 3)); // 8
console.log(multiply(4, 2)); // 8
console.log(greet()); // Welcome, Guest!
console.log(greet("Elena")); // Welcome, Elena!