Sign in
Log inSign up

Scope in javascript

harish kumar's photo
harish kumar
·Aug 10, 2021·

5 min read

What is scope in JavaScript and why is it important 🙄?

Scope refers to the accessibility of variables in different parts of the code. You can use the following three keywords to declare the scopes of variables.

  1. var
  2. let
  3. const

Let's discuss these first,

var

The var keyword declares a variable in the current execution context (aka current scope).

  • If the declaration appears in a function - it is treated as a local variable.

  • If it's outside of any function - it is a global variable

Example

// var demonstartion

var x = 10;  //global scope as it is not declared inside a block and can be used anywhere in the code

function var_demo(){
    var y = 20;
    console.log(`The value of x  inside block is : ${x}`);
    console.log(`The value of y inside block is : ${y}`);
}

var_demo()

The code will work fine and produces the following output

The value of x inside the block is: 10
The value of y inside the block is: 20

But, if you try to access the variable y outside the function, it will throw a not defined error!

// var demonstartion

var x = 10; 

function var_demo(){
    var y = 20; //cannot access outside the function
}

var_demo()

console.log(`The value of x  outside block is: ${x}`);
console.log(`The value of y outside block is: ${y}`);
The value of x  outside block is: 10
.\Scope.js:12
console.log(`The value of y outside block is: ${y}`);
                                                 ^

ReferenceError: y is not defined

Apart from there are many other things like Closures, which plays an important role in the scope of a variable declared using var

let

The let keyword declares a variable, which is limited to the scope of the block statement. You can understand by following the below example

function call() {
    let y = 10;
    {
        let y = 20;
        console.log(`Value inside block is : ${y}`)
    }
    console.log(`Value outside block is: ${y}`)
}
call()

The variable y is treated as a new variable inside the block( { ..}) and it is destroyed as soon as, it came out of the block.This is called Shadowing

Output:

The value inside block is: 20
The value outside block is: 10

When the variable y is declared using the var keyword.It will print 20 two times as the scope of var is associated with the current execution context

Same Program using var

function call() {
    var y = 10;
    {
        var y = 20;
        console.log(`Value inside block is : ${y}`)
    }
    console.log(`Value outside block is: ${y}`)
}
call()

Output:

The value inside the block is: 20
Value outside block is: 20

Now you can understand the difference between var and let.

Const

When a variable is declared using the const keyword, it creates a read-only reference to the value. This means you cannot re-assign the identifier as we did in the last program. Both const and let are block-scoped.

Example:

const y = 10;
y = 10    //throws error ( Assignment to constant variable. )

But when it is used with array and object the values can be changed.(but re-assigned)

const arr = [10,20,30]

arr[2] = 40 //no error

console.log(arr);

Output

[ 10, 20, 40 ]
const obj = {
    name:"scope",
    job:"to confuse people",
    solution:"follow harish kumar's blogs on hashnode"
}

obj.name = "javascript"

console.log(obj)

Output:

{
  name: 'javascript',
  job: 'to confuse people',
  solution: "follow harish kumar's blogs on hashnode"
}

Now, we know about var,let,const and the scope of the identifiers declared using these keywords.

So when should you use var, let and const? Developers usually prefer to const and then let and then var.

It's time to move on to scoping. We will discuss the following scopes,

  1. Block
  1. Function

  2. Lexical

Block Scope

In any language, block refers to the piece of code which is enclosed in curly braces ({..}).let and const are block-scoped meaning you cannot use identifiers declared using these two keywords outside the block. Here's the example,


let name = "JS"

{
    // BLOCK
    let name ="Node JS"
    console.log("Name inside block is "+name);
}

console.log(`Name outside block is ${name}`);

You might have already guessed that this might the output 👀

Name inside block is Node JS
Name outside block is JS

Function Scope

It's very simple to understand. A variable declared inside a function cannot be used outside a function. Identifiers declared using var are functional scoped.

function call(){
    var name = "Node JS"
    console.log(`Name inside fucntion: ${name}`);
}
call()
console.log(`Name inside fucntion: ${name}`);

As you guessed first it will print the name as "Node JS" and throws an error of "name not defined". Since var is functionally scoped.

Lexical Scoping

To understand this let's consider a function name outer and we are declaring a variable named x in it. The function also contains another function name inner (a nested function).In this case, the function named inner(child) has access to the outer(parent) function's scope. This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested.

function outer(){
    let x = 20;
    function inner(){
        console.log(`The value of x is : ${x}`);
    }
    inner()
}
outer()

The inner has access to the scope of outer function and thus it prints 20.

The value of x is: 20

Well... I think you have learned something useful today. Take care ✌

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct