0

Scope in ES 6

As we JavaScript/EcmaScript is the de facto language of the browser and the way in which scoping works in it is very confusing to those who are coming from other languages like Java, C#, C++ and so on.  Here I will try to give you clarity on how scope works with ES6 and ES Next.

Untill ES 5 there was only one option available to declare variable with “var” keyword that has changed from ES 6 onwards. Now from ES 6 onwards we have two more ways to declare varibale with “let” and “const” keywords.

Will see how scope works with an example

function fn() {
var varOuter = "first time";
console.log(varOuter); //first time</code>

let letOuter = "first time";
console.log(letOuter); //first time
if (true) {
var varInner = "str";
console.log(typeof (varInner)); //string
let letInner = "str";
console.log(typeof (letInner)); //string
const constInner = "str";
console.log(typeof (constInner)); //string
}

console.log(typeof (varInner)); //string
console.log(typeof (letInner)); //undefined
console.log(typeof (constInner)); //undefined

//I have used typeof() above so it is showing 'undefined' else it would throw error
//console.log(letInner);//letInner is not defined
//console.log(constInner);//constInner is not defined
var varOuter = "second time";
console.log(varOuter); //second time

//let letOuter = "second time";//Identifier 'letOuter' has already been declared
}
fn();
console.log(typeof (varInner)); //undefined
console.log(typeof (letInner)); //undefined
console.log(typeof (constInner)); //undefined

//I have used typeof() above so it is showing 'undefined' else it would throw error
//console.log(varInner); //varInner is not defined
//console.log(letInner); //letInner is not defined
//console.log(constInner); //constInner is not defined

If you observe closely here is what you can figure out

 

var: Available within the function in which it is declared.

let and const: Only available within the block in which it is declared.

 

var: “Hoisted” to the top of the function.

let and const: Not “Hoisted” to the top of the function.

 

var: Varible name may be declared a second time or more than once in the same function and wouldn’t throw error.

let and const: Only once it can be declared in a block and if we try second time it will throw error.

 

If you like the post please share your valuable comments 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.