Wednesday, 27 October 2021

SCOPING IN JAVASCRIPT




 SCOPING:

Scoping controls how our program variables are organized and accessed, i.e Scoping asks the program where do the variables are present /  where can access the variable and where the variable is not allowed to access. In javascript, there is lexical scoping. Lexical scoping is controlled by the placement of functions and blocks in code. There are three types of scopes

  • Global Scope
  • Function Scope
  • Block Scope

GLOBAL SCOPE:

Global scope is where the variable is declared outside of any block i.e this variable can be accessed everywhere in the program.

Example:

let x = 1;
let y = 2;

for (let i = 1; i < 5; i++) {
x *= i;
y *= i;
}

console.log(x, y)

// Result
// 24 48


In the above case, the variables x and y can be accessed within for block but the variable i cannot be used outside the block. So the variables x & y  are global variables.

FUNCTION SCOPE:

Function scope is the variables are declared inside the function. These variables cannot be accessed outside the function. The. function scope is also called the local scope.

let a = 0;
const x = function (y) {
a = a + y;
}

console.log(y);

//Output
// Reference error

 
In the above case, we want the  variable to log in to the console. But variable  is the function scope variable, when we access the variable out of its scope, would give us a reference error.

BLOCK SCOPE:

The variables which are declared inside the code blocks have the block scope. These variables cannot be accessed outside the block, however, this only applies to let and const variables. If the variable is declared by var this can be accessed outside the block. So let and const are said to be block variables.
And in strict mode, the functions are also block scoped.


Thank You!!!!

Have A Good Day !!!!


No comments:

Post a Comment

Array Destructuring

  Destructuring  Destructuring is an ES6/ES2015 feature. Destructuring allows us to break down the complex data structure into a simple data...