Block scope variables in ES6

Block scope variables


In this post, we are going to look into the new block scoped variable in ES6.

ES6 has come with good features in variable declaration. Before ES6 We are declaring a variable using the var keyword, this is basically the global variable.

ES6 has introduced the new variables called Let and Const, Both let and const declare as local variables with block scope rather than function scope

Let

The let variables are block scoped variables available within the block itself, we can't able access the variable outside of the block

Without Let



With Let


Const

Declaring a variable with const is similar to let when it comes to Block Scope.
const variables must be assigned a value when they are declared.

If we assign a primitive value to a constant, we cannot change the primitive value.

const test= 2; 
test = 3.14; // This will give an error 
test = test + 10; // This will also give an error

Constant Objects can Change But you can NOT reassign a constant object.

Related Articles



Comments