DEV Community

Cover image for What is SCOPE in JavaScript?
Sakib Ahmed
Sakib Ahmed

Posted on

What is SCOPE in JavaScript?

It's all about accessing variable. The accessibility or validity of a variable is determined by it's SCOPE.
Suppose a variable is declared inside a function. And you try to access the variable outside that function.
Then you will encounter an error that the variable is not defined.

Ex:
example of not defined variable

But Why?
Because the scope of that variable is limited to that function and you can't access that.

Scope type

There are two types of scope in javascript.

  1. Local Scope
  2. Global Scope

scope in javascript

What is Local Scope.

Whenever a variable is declared inside a function it is said to have local scope.

javascript local scope examplen

A variable declared inside a function can only be used inside that function. We can't access it outside the function

What is Global Scope.

The variable which can be accessed everywhere are said to have global scope. These variable are not declared inside any function.

javascript global scope example

A global variable can be accessed by any function.
Here, we assigned value of a variable which is outside the function.

scope in js

In the above snippet, we have a variable globalScope whose scope is not limited to any function and thus can be accessed everywhere, even within a function

You are done, but wait...

There are something call Hoisting.

Hoisting

In JavaScript, all variable declarations are moved to the top of their scope. This is known is hoisting.

In JavaScript, a variable can be used before it is declared! wait what? yes, read it right.

I mean that:

var newVar = 10;
...
...
Enter fullscreen mode Exit fullscreen mode
...
...
var newVar = 10;
Enter fullscreen mode Exit fullscreen mode

Will result the same output, because all the variable are automatically moved to top when we run the program.

This concept is known as hoisting.

Conclusion

A scope of a variable is the block where it can be accessed and used.

If a variable is declared inside a function it is known as a local variable.
If a variable is declared globally, it is said to have a global scope.

Hoisting is a JavaScript's behaviour of moving variable declarations to the top.

See yaa...

Top comments (0)