⚡
Functions and Scope
Beginner
90 XP
35 min
Lesson Content
Functions and Scope
Functions are reusable blocks of code that perform specific tasks. They help organize code and avoid repetition.
Function Declaration
function greet(name) {
return 'Hello, ' + name + '!';
}
console.log(greet('Alice')); // Hello, Alice!Arrow Functions
const add = (a, b) => {
return a + b;
};
// Shorthand for single expression
const multiply = (a, b) => a * b;Scope
- Global scope: Variables accessible everywhere
- Local scope: Variables inside functions
- Block scope: Variables inside {} blocks (let, const)
Return Values
function calculateArea(width, height) {
return width * height;
}
let area = calculateArea(5, 10); // 50Example Code
Create functions to perform calculations
// Function to add two numbers
function add(a, b) {
return a + b;
}
// Function to calculate area
function calculateArea(width, height) {
return width * height;
}
// Arrow function to greet
const greet = (name) => {
return 'Hello, ' + name + '!';
};
// Test the functions
console.log('Sum:', add(5, 3));
console.log('Area:', calculateArea(4, 6));
console.log(greet('World'));Expected Output:
Sum: 8 Area: 24 Hello, World!
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code