未分類

JavaScript – Blocks and IFFES

Let’s look at the new way to create IFFES!

Since variables declared with let and const are block-scoped which means these variables are defined inside of a block, and from the outside of the block they are not accessible.
This is exactly what we want,
–> Data Privacy

Before ES6, we use IFFES for that, it seems that in ES6, we have a much simpler way to achieve data privacy since all we have to do is to use a block.

A block is not restricted to if statement, for or while loop, we can also create a block simply like this

{   
//your code
}

And we just created a block !

{     
  const a = 1;
  let b = 2;
}

console.log(a + b);
//Uncaught ReferenceError: a is not defined

Since these values are not accessible from outside of the block, we got an error here. This reinforces the fact that they are block-scoped, not function-scoped.

So what we have here now is exactly like an IFFE, we created some data here that is not accessible from the outside.

It’s so much easier to write like this.


ES5 version to create variables that are inaccessible from outside

(function(){   
  var c = 3;
  var b =2;
})();
console.log(c+b);

This was the old way.


What if

{     
  const a = 1;
  let b = 2;
  var c = 3;
}
console.log(c);

The answer is

3 

This is because variable declarations with var keyword it does not matter whether they are inside of a block or not since

they are function-scoped. (instead of block-scoped)

Standard

Leave a comment