Menu
Coddy logo textTech

Block scope - let & const

Lesson 3 of 9 in Coddy's Tricky parts of Modern Javascript (ES6+) course.

What is block scope ? even before that , what is scope of a variable ? 

Scope of a variable is nothing but the area in which the given variable is accessible , i.e. we can use the variable only within his scope.

The variables before ES6 , were declared by keyword var . Such variables had only Global Scope and Function ( Local ) Scope.

In ES6 , we can declare variables using let and const keywords , which have block scope. 

A block is nothing but , an area enclosed within a pair of starting  and closing curly brackets within which we can write JS code ex. { // any code }.

{
  let x = 2;
}
// x can NOT be used here
// as x is not accessible outside the above block

The similar case applies to const , as it also has block scope.

The variables declared with const must be initialized , and we can not change/assign new value after first initialization !

const pi = 3.14;
pi = 4.2 // Error , invalid assignment to const

 

As mentioned earlier , var doesn't have block scope, but has a Global/Function level scope.

{
  var x = 2;
}
// x CAN be used here , as x has global scope

 

Some important key points : 

  • Variables defined with let / const cannot be Redeclared.
  • Variables defined with let / const must be Declared before use.
  • Variables defined with let / const cannot be hoisted.
challenge icon

Challenge

Easy

Create two variables inside given function - name = "Coddy" using let, age = 25 using const. print these values using console.log().

Try it yourself

function getInfo() {
    // Write code here
}

All lessons in Tricky parts of Modern Javascript (ES6+)