Function Scope: Your Bedroom

Grade 9, page 3 of 11. A one-minute read.

Variables created inside a function (including the function's parameters) can only be seen inside that function. They're created fresh every time the function is called, and they disappear when the function finishes:

JavaScript
function calculateTip(bill) {
  const tipRate = 0.1;
  const tip = bill * tipRate;
  return tip;
}

console.log(calculateTip(200));
console.log(typeof tipRate);
console.log(typeof bill);

It prints

20
undefined
undefined

Outside the function, tipRate, tip and bill don't exist. (typeof is a safe way to check this: it gives "undefined" for a missing variable instead of throwing an error.)

This is actually great news. It means two different functions can use the same variable names without stepping on each other's toes:

JavaScript
function cookRice() {
  const minutes = 20;
  console.log(`Rice takes ${minutes} minutes`);
}

function boilEggs() {
  const minutes = 8;
  console.log(`Eggs take ${minutes} minutes`);
}

cookRice();
boilEggs();

It prints

Rice takes 20 minutes
Eggs take 8 minutes

Two different minutes variables, in two different rooms. No problem at all. They're like two people both called Lucas living in different houses. Nobody gets confused, because they never meet.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning