Shadowing: When Names Collide

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

What happens if an inner scope creates a variable with the same name as one in an outer scope?

JavaScript
const name = "Global Gary";

function introduce() {
  const name = "Local Lucy";
  console.log(`Inside: ${name}`);
}

introduce();
console.log(`Outside: ${name}`);

It prints

Inside: Local Lucy
Outside: Global Gary

Inside the function, the inner name hides the outer one. This is called shadowing: the inner variable casts a shadow over the outer one, so the outer one can't be seen from inside. The outer variable isn't changed at all; it's just temporarily hidden.

Shadowing is allowed, but it can be confusing to read. ("Wait, which name is this?") Where you can, give your variables different, descriptive names.

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