DEV Community

Ruslan Khait
Ruslan Khait

Posted on

Scoping In JavaScript

In JavaScipt, scoping is the able of accessing variables. Back in the day, you could only use the keyword “var” to declare a variable. It was a terrible practice of declaration. When variables are declared with the keyword “var”, it can’t have a block scope. For example, when declaring a variable inside a {} block, it can also be accessed outside of the {} block.
ex:

{
   var a = 1;
}
// a can be used here
Enter fullscreen mode Exit fullscreen mode

Meaning you could of created a variable inside of the block and declare the same variable locally. Both of these variables would of modified the variable.
To fix this problem, JavaScript introduced two new keywords: “let” and “const”. “let” is used to declare a variable inside a block scope. “const” keyword is used when you don’t want the variable to change it’s value after it was declared.

The two ways of scoping is Global scope and Function Scope. Any variable declared outside of a function can be used Globally. These variables can be accessed from anywhere in the file.
ex:

let x = 0 // Global Scope
Enter fullscreen mode Exit fullscreen mode

A variable declared inside a function aren’t accessible or in other words, visible from outside the function. This is known as function scope. It is accessible only within the scope of the function.
ex:

function x(){
   let y = 1 // Function Scope
}
Enter fullscreen mode Exit fullscreen mode

Oldest comments (1)

Collapse
 
jvictor940 profile image
Jvictor940

Interesting, Thank you!