Scope in JavaScript

Scope in JavaScript

·

5 min read

In this article, we will try to understand what is Scope in JavaScript.

Scope

The current context of execution. The context in which values and expressions are "visible" or can be referenced. If a variable or other expression is not "in the current scope," then it is unavailable for use. --MDN Reference

Scope simply means where you can access a specific variable or a function in the code.

There are four types of Scope:

1. Block Scope
2. Function Scope
3. Global Scope
4. Lexiacal Scope


1. Block scope - It is a new concept that came into the picture when ES6 introduced two new topics: let and const. Everything in JavaScript that is written inside a {}, these curly braces cannot be accessed outside. If we will try to do so, we will get a ReferenceError.

Consider an example:

{
let name = "Joe";
const age = 12;
}
console.log(name); // ReferenceError: name is not defined
console.log(age); // ReferenceError: age is not defined

Note: variables defined with var do not have block scope.

One more example to have a better understanding of block scope:

function display(){
    if (true)
    {
       const a = 100; 
    }
    console.log(a);
}
display();

Can you guess the output?

The output will be :

ReferenceError: a is not defined

Because the if statement is creating a block, and hence we cannot access variable a outside block.


2. Function scope - Variables and functions that are declared or defined inside a function become local to that function and cannot be accessed outside the function. Variables defined with var, let, and const, all behave the same way when declared inside a function, they all have function scope.

Consider an example:

function myFunction(){
    var a = 10;
    let b = 20;
    const c = 30;
}
console.log(a); //ReferenceError: a is not defined
console.log(b); //ReferenceError: b is not defined
console.log(c); //ReferenceError: c is not defined

Another example:

function myFunction(){
    var a = 10;
    function innerFunction(){
        console.log(a);
    }
}
innerFunction(); // ReferenceError: innerFunction is not defined


3. Global scope - The variables that are defined outside a function or a block have global scope, and these types of variables are called global variables. Global variables can be accessed anywhere in a program. Variables defined with var, let, and const, all behave the same way when declared outside a function or a block, they all have global scope.

Example1:

var x = 100;
let y = 400;
const z = 900;

function print()
{
    console.log(x); 
    console.log(y);
    console.log(z);
}
print();

The output of the above program is:

100
400
900

Example2:

var marks1 = 40;
let marks2 = 50;
const marks3 = 35;


{
    console.log(marks1);
    console.log(marks2);
    console.log(marks3);
}

The output of the above program is:

40
50
35

Now let's see some important points to remember:

  • If we will assign a value to a variable that has not been declared, it will automatically become a global variable no matter where it is defined.

Example1:

function print() {
    a = "hello";
}

print();

console.log(a); // hello

Example2:

{
    greet = "Good Morning";
}

console.log(greet); // Good Morning
  • In "Strict Mode", variables cannot be used without declaration. To know more about Strict Mode, you can refer JavaScript Strict Mode.

Note: It is not a good practice to declare global variables because any code in a program can change the values of global variables and it can produce unexpected results.

4. Lexical Scope - An item's lexical scope is the place where it is present or defined.

Let's understand this topic by an example:

console.log("Welcome to Programiz!");

const author = "Helen Keller";

function getAuthor(){
    return author;
}
console.log(getAuthor());

Can you answer that which one is the variable author's lexical scope? Is it global scope or the getAuthor function scope?

The answer is global scope because author is defined in the global environment.

Only code that is present inside the lexical scope of an item can access the item.

Example:

function showBook() {
  const book  = "The Story of My Life";
  return book;
}
function showYear() {
  const year = 1902 ;
  return year;
}

function bookInfo(){
    const info = book + " was published in " + year + ".";
    return info;
}
console.log(bookInfo());

What is the output of the above program according to you?

This program will throw an error:

ReferenceError: book is not defined

Because variable book is lexically present in the showBook function, and code within an item's lexical scope can only access the item.

Similar is the case for variable year.

The Solution of the above program could be:

function showBook() {
  const book  = "The Story of My Life";
  return book;
}
function showYear() {
  const year = 1902 ;
  return year;
}

function bookInfo(){
    const info = showBook() + " was published in " + showYear()+".";
    return info;
}
console.log(bookInfo());

Now, the output will be:

The Story of My Life was published in 1902.

Because now we are calling the functions ( getBook and getYear ) instead of variables and since these functions are in the lexical scope of the bookInfo function, accessing them will not throw any error.


✨ That's all for this article!! I hope this article will help you to gain a better understanding of Scope in JavaScript.

If you found this article helpful, please like and share it, and feedback is always appreciated.