javaScript Interview cheatSheet

javaScript Interview cheatSheet

Understanding Scope in Depth for Interview

If interviewer asked about scope we can give below answer straight forward

Scope in JavaScript defines accessibility of variables, objects and functions.

Lets understand it on more depth

There are 2 types of Scope in JavaScript-

1-Local Scope
2. Global Scope

Local Scope is further Divide into Two parts

  • Block Scope
  • Function Scope

Local-Scope

Variables declared within a JavaScript function, become LOCAL to the function.

Block Scope

The scope created with a pair of curly braces

Actually, this feature comes up with ES6(2015) before that there are only two scope are exist which is function scope and global scope ES6 introduced two important new JavaScript keywords: let and const. These two keywords provide Block Scope in JavaScript.

{
  const x = 25;
}

//outside of the block or Curley braces we cannot used "x"
{
  var x = 25;
}

//outside of the block or Curley braces we can used "x"

if we initialize the value by var then it's not block scope and it can be accessed by outside the Curley braces

Function Scope

Local variables have Function Scope,They can only be accessed from within the function.

JavaScript has function scope: Each function creates a new scope.

Variables defined inside a function are not accessible from outside the function.

Variables declared with var, let and const are quite similar when declared inside a function.

// code here can NOT use myName

function name() {
  let myName = "Piyush";
  // code here CAN use myName
}

// code here can NOT use myName

Global Scope

Global variables can be accessed from anywhere in a JavaScript program. Variables declared Globally (outside any function) have Global Scope.

Variables declared with var, let and const are quite similar when declared outside a block.

They all have Global Scope:

var x = 10 ;   // Global Scope

let x = 10;     //Global Scope

const x = 10 ;   // Global Scope
let name = "Piyush";
// code here can use name

function myName() {
// code here can also use name
}

Conclusion

The scope is a policy that manages the availability of variables. A variable defined inside a scope is accessible only within that scope, but inaccessible outside.

In JavaScript, scopes are created by code blocks, functions, Global.

While const and let variables are scoped by code blocks, functions or modules, var variables are scoped only by functions or modules.

Scopes can be nested. Inside an inner scope you can access the variables of an outer scope. Hopefully, my post has helped you understand the scope better!