DEV Community

Patkul Shah
Patkul Shah

Posted on

ES6 Block Scope is The New IIFE

I will be summarizing how we don't really need IIFE anymore when using ES6 Block Scope. Specifically, we will learn how let and const are going to be super useful! Basically, let and const is beneficial if you need to scope something to a block, or if you want to make a variable that cannot be changed by accident or on purpose.

Background on IIFE (skip if you already know):

An IIFE function runs itself immediately, and it creates a scope where nothing is going to leak into the parent scope. In our case, nothing is going to leak into the global scope of the window.

Creating a named function pollutes the global name space. It also means the named function is hanging around. With the function hanging out, oh-so readily available, it could accidentally be invoked again. IIFE isn’t named and therefore can’t accidentally be called later — avoiding any potential security implications.

If you try to call name in the console now, it’s not undefined, it’s blank because, like I mentioned, it’s just blank because that is a property that lives on the window in JavaScript.

HERE COMES LET AND CONST TO THE RESCUE!

With let and const variables, we don’t need a function for our variables to be scoped to that.

Why? Because let and const use block scope.

Let’s start over with a const instead of a var

If we call this in the console, we’ll see 'Awesomeness', but if we wrap it in curly brackets ( see first lines of code below )

Our const is going to be scoped to that block. If you try to call name in the console, we’ll get the window’s name equal to "result", whatever that means(you can explain it in the discussion section!). But if we add a console.log to our block ( see last lines of code above )

You don’t the IIFE stuff anymore. You’re using let and const because they are going to be scoped to that block. Let me know what other examples you guys can think of in the discussion section below!

Top comments (1)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

ES6 Block Scope is my new friend, to variable naming.