Scope in Javascript

Table of contents

No heading

No headings in the article.

What exactly is the scope? Why do we need it?

Scope determines the accessibility/usage of variables, functions and objects from different parts of the code.

Before diving into its types, there is a term called lexical scope. Let's try to understand that first.

Lexical scope is the concept of determining the scope of a variable based on its place of declaration, not on the place of its usage.

There are three types

  1. Function scope

  2. Block scope (after ES5)

  3. Global scope

Function scope

Variables declared inside functions are local to that function only and are not visible/accessible outside the function no matter you declare them with var or let or const keyword.

function getName(){
    var name = 'Meghana';
    return name;
}

console.log(name); // ReferenceError: name is not defined

Global scope

Variables declared outside functions or block automatically become global scope irrespective of declarative keywords let , const or var.

  • The global scope is the window object.

  • Global variables defined with the var keyword belong to the window object

let name = 'Meghana';
function printName(){
    console.log(name); // Meghana - can access from here since name is global variable
}

Block scope

ES6 introduced two new keywords let and const which provide block scope i.e, anything declared using keywords let and const inside curly braces { } is block scoped.

{
    let name = 'Meghana'
    console.log(name); // Meghana
}
console.log(name); //Reference error: name is not defined
{
    const name = 'Meghana'
    console.log(name); // Meghana
}
console.log(name); //Reference error: name is not defined
  • Automatically a variable becomes a global variable, if no keyword is used while declaration, it becomes global by default. in strict mode, however, you have to specify the declaration keyword let, const or var

      myFunction();
    
      // code here can use Meghana
    
      function myFunction() {
        name = "Meghana"; // automatically global since by default if no keyword used while declaring, it becomes global by default
        console.log(name)
      }
    

    That's all about the scope. Hope you enjoyed the read. Please post suggestions if any. See you all :)