Lesson 11 of 18

Functions & Scope 🔧

🎯 Grades 9–12 ⏱ ~35 minutes 💚 Intermediate

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));  // 7

Arrow 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)); // B
💡
Arrow 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 here
🔧">Grade 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?

AA function that only runs once
BA modern, concise function syntax using =>
CA function with no parameters

What does scope mean in JavaScript?

AThe size of the function
BWhere a variable is accessible in your code
CHow fast the function runs

What does a function return statement do?

APrints to the console
BStops the function and sends a value back
CCreates a new variable