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 blockThe similar case applies to const , as it also has block scope.
The variables declared with
constmust 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/constcannot be Redeclared. - Variables defined with
let/constmust be Declared before use. - Variables defined with
let/constcannot be hoisted.
Challenge
EasyCreate 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+)
2Let's dive in
Block scope - let & constThe Arrow FunctionsSpread and Restfor - of loopClassesPromisesAsync & Await