Scope (JavaScript)

Scope is the part of a program where a variable is visible and can be used. JavaScript has global scope, function scope, and block scope.

JavaScript

A variable declared inside a function or block only exists there; code outside cannot see it. Variables declared at the top level are in the global scope and reachable everywhere.

let and const create block scope (limited to the nearest { }), while var only respects function scope.

Examples

JavaScript

function outer() {
  let secret = 42;
  return secret;
}
console.log(outer());
// console.log(secret) would throw — out of scope

Output:

42

Learn it in a lesson

See also

Back to the Dictionary