Blocks in ES6

We use for the data privacy. 

IIFE : Immediately  invoked function expression. In ES5 we were using IIFE for data privacy.

But in Es6 we have more better approach for the data privacy and we can use block instead

Now block not only means if condition , for loop . But we can create the block simply by using two curly braces

{

}

Example :

//Es5

//Es5 using IIFE

(function(){

var a = 2;

var b = 5;

})();

console.log(a+b);

var are function scoped. So, can not be accessed outside the self calling function

//Es6

<script>

//Es6

{

   let a = 2;

   const b = 5;

}

console.log(a+b);

</script>

Output : Uncaught Reference Error: a is not defined at a6.html:9

a and b can’t be accessed outside the block

Note : They are block scoped and not the function scoped

Again take a example :

{

var a = 10;

}

console.log(a);

Output : 10; // Because the var is function scoped

 

Site Footer