Who Sees What?

1. Local Variables

A variable declared inside a function is visible ONLY inside that function.

function showMessage() {
  let message = "Hello!"; // local
  alert(message);
}
alert(message); // ERROR!

2. Outer Variables

A function can access variables declared outside.

let userName = 'John';

function showMessage() {
  userName = 'Peter'; // Changed the outer variable
  alert(userName);
}
Important

If a variable is declared inside a function with the SAME name as an outer one, the local variable " shadows " the outer one.

Tip

Try to minimize the use of outer variables. A good function is a " black box " that relies only on its arguments.