Scope in Javascript

Scope in Javascript (JS)

5 Likes

Scope means variable access. What variable do I have access to when a code is running? In Javascript by default, you’re always in the root scope i.e. the window scope. The scope is simply a box with a boundary for variables, functions, and objects. These boundaries put restrictions on variables and determine whether you have access to the variable or not. It limits the visibility or availability of a variable to the other parts of the code. A scope can be defined in two ways –

  • Local Scope allows access to everything within the boundaries (inside the box)
  • Global Scope is everything outside the boundaries (outside the box). A global scope can not access a variable defined in the local scope because it is enclosed from the outer world, except if you return it.
  • Block Scope is everything inside the boundaries but it works only for var and const keywords. It does not work with the var keyword.

Example: The code given below will give you an error because “name” is defined within the boundary (local scope) of the showName() function. You can not have access to this variable outside the function.

NOTE: The code below shows an error due to a typo in the function call, causing an error before the intended scoping error is raised by the console.log call.

  • Javascript

function showName()

let name - "radhika" ;

showname()

console.log(name);

Output:

Uncaught ReferenceError: showname is not defined

Example: Now, take a look at the code given below and see how you can access the variable “name” defined in the local scope.

  • Javascript

function showName

let name = "radhika" ;

console.log(name);

showName();

Output:

radhika

Example: Here we will use block scope.

  • Javascript

function fun() {

let a = 10;

console.log(a);

}

console.log(a);

Output:

Uncaught ReferenceError: a is not defined

Example: The below example will not throw an error and give 20 20 as output as block scope does not work with var.

  • Javascript

let a = 10;

function fun() {

let a = 20;

console.log(a);

}

console.log(a);

5 Likes