Friday, July 3, 2020

Variable scopes in JavaScript

In JavaScript, there are two types of scopes

  1. Global Scope – Scope outside the outermost function attached to window.
  2. Local Scope – Inside the function being executed.

Let’s look at the code below. We have a global variable defined in first line in global scope. Then we have a local variable defined inside the function fun().

Code snippet:

let globalLet = "This is a global variable"; 

function fun() { 

  let localLet = "This is a local variable"; 

  console.log(globalLet); // This is a global variable 

  console.log(localLet); // This is a local variable 

fun();

console.log(globalLet); // This is a global variable 

console.log(localLet);

Output

No comments:

Post a Comment