DEV Community

Cover image for Scope in JavaScript
Rakshambika
Rakshambika

Posted on

Scope in JavaScript

What is Scope?

Scope determines the accessibility (Visibility) of your variables. It defines where you can see, use, or change a specific variable in your code.

There are three types of scope in JavaScript.They are

      - Global Scope
      - Block Scope
      - Function Scope
Enter fullscreen mode Exit fullscreen mode

Global Scope:

  • Variables that are declared outside of any function.
  • These Global scope variables can be accessed from anywhere.
<script>
        let a=10;
        const b=20;
        var c=30;

        function add(){
            console.log(a);
            console.log(a+b+c);
        }
        add();
</script>
Enter fullscreen mode Exit fullscreen mode

Output:

10
60
Enter fullscreen mode Exit fullscreen mode

Here, the variables a,b and c are accessible inside add() because functions can access global variables.

Block Scope:

  • Before ES6, JavaScript variables could only have Global Scope or Function Scope.
  • ES6 introduced two important new JavaScript keywords: let and const.
  • These two keywords provide Block Scope in JavaScript.

Variables declared with let and const inside a block ({}) are accessible only within that block.

<script>
       {
            let d=10;
            const e=25;
            console.log(d+e);
        }

        console.log(d+e);
    </script>
Enter fullscreen mode Exit fullscreen mode

Output:

35
Uncaught ReferenceError: d is not defined
Enter fullscreen mode Exit fullscreen mode

Why this Uncaught ReferenceError means variables declared with let and const are block scope. So we can't access them outside the block.

Function Scope:

Variables declared with var, let, or const inside a function are only accessible within that function.

<script>
function function_scope(){
            let name="Raksha";
            var num=25;
            const pi=3.14;

            console.log(name);
            console.log(num);
        }

        function_scope();
        console.log(num);
        console.log(pi);
    </script>
Enter fullscreen mode Exit fullscreen mode

Output:

Raksha
25
Uncaught ReferenceError
Enter fullscreen mode Exit fullscreen mode

Why this Uncaught ReferenceError means variables declared inside a function have function scope. So we can't use them outside of the function.

Top comments (0)