Lesson 11 of 18
Functions & Scope 🔧
What You'll Learn
- Declare and call JavaScript functions
- Understand arrow functions
- Understand what scope means
Function Declarations
JavaScript
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('Alex')); // Hello, Alex!
// Function expression
const multiply = function(a, b) {
return a * b;
};
// Arrow function (modern, cleaner)
const add = (a, b) => a + b;
console.log(add(3, 4)); // 7Arrow Functions
JavaScript
// Multi-line arrow function
const getLetterGrade = (score) => {
if (score >= 90) return 'A';
if (score >= 80) return 'B';
if (score >= 70) return 'C';
return 'F';
};
console.log(getLetterGrade(85)); // BArrow Functions
Arrow functions are the modern standard. For single expressions, you can skip the braces and return: const double = n => n * 2;
Scope
JavaScript
const globalVar = 'I am global'; // accessible everywhere
function myFunction() {
const localVar = 'I am local'; // only inside function
console.log(globalVar); // works
console.log(localVar); // works
}
console.log(globalVar); // works
console.log(localVar); // ERROR - not accessible hereGrade Calculator
Write an arrow function called calculateGrade(score) that returns a letter grade. Write another function called printReport(name, score) that uses calculateGrade and logs a formatted result like: "Alex scored 87 which is a B".
Quick Check
What is an arrow function?
What does scope mean in JavaScript?
What does a function return statement do?