DEV Community

himanshuc11
himanshuc11

Posted on

Variable Declarations and Scoping in JavaScript

There are only three types of variable declaration inside JavaScript. These are
let, const and var declarations

Before we understand these declarations we need to know about scoping.Scoping simply answers the basic question, "Where is this variable name valid?". This can also be thought of where can I, access this variable from.

There are 2 types of scoping

Block Scoping

In this type of scoping, the variables are valid only to the nearest enclosing block and not outside it. They are essentially valid only from "{" to the "}". So we simply look for the innermost "{" in which the identifier is present. It is now valid until it's corresponding "}" is not encountered.

{
// Block Scope of a variable 
}

1{
   // Variables declared here are valid from 1  to 1' and even valid inside 2 to 2' as its enclosing block is 1'
    2{
        // Variables declared here valid only from 2 to 2'
    2'}
1'}
Enter fullscreen mode Exit fullscreen mode

Lexical Scoping

Lexical scoping allows variables to be valid inside the whole function inside which they are declared and ignore all block level scoping. Here the variable once declared inside the function can be accessed inside any level of the function

function dev() 1{
// Lexically scoped variables, are valid from 1-1' 
1'}

function dev1() 1{
    2{
        // Lexically declared variable x
    2'}
    // x is valid here as it is lexically valid from 1-1' 
1'}
Enter fullscreen mode Exit fullscreen mode

Now we understand scoping so we can discuss let, const and var in detail.

let and const are block level scoped and var is lexically scoped.

Difference between let and const

let is used to refer to variables that may change in the future.

const is used to declare a read-only reference to the value. A const statement does not allow re declaration or re-assignment of variables

Common confusion

Using const in objects makes a constant reference to the object, not the object constant. The object is still mutable

// This is valid JS as we are mutating the object, not the reference
const obj = {}
obj.key = "value"

// This is invalid JS, as we are mutating the reference itself
const obj1 = {}
obj1 = {"key": "value"}
Enter fullscreen mode Exit fullscreen mode

Another common confusion is that var creates global variables, which is not entirely true.
var is used to create variables with lexical/functional scope, so var becomes a global variable only when it is declared outside any function

// variables declared here are globally scoped

function dev() {
// variables declared here are not globally scoped, and are restricted to the dev
}
Enter fullscreen mode Exit fullscreen mode

To get a video tutorial on this concept,
https://www.youtube.com/watch?v=wtBbanu-kUY

References:
https://developer.mozilla.org/en-US/docs/Glossary/Scope
https://javascript.info/closure

Top comments (0)