For the first 100 days of 2021, as part of #100DaysOfCode, I am re-introducing myself to common JavaScript concepts and blogging about them! For this post, I am going to talk about closures and IIFEs and how important they can be in JavaScript programming.

Closures

In JavaScript, functions are considered to be “first-class” because, like other variables, they can be assigned as a value, passed as an argument and even returned from other functions! Because JS functions are regarded this way, each time they are created, they come with an ability to utilize variables from outside its scope. This ability is known as a closure.

Closures refer to an enclosed function’s access to its surrounding state, the lexical scope. For example, in this short code snippet:

let A = "Hello, World!"
function greeting() {
  console.log(A) 
}

greeting() // --> Hello, World!

Despite A not being defined outside the scope of greeting(), it is still accessible within the function. Let’s see what happens if we change the value of A below the definition of the greeting() function:

let A = "Hello, World!"
function greeting() {
  console.log(A) 
}

A = "Hello, Other World!"

greeting() // --> Hello, Other World!

#javascript #100daysofcode

How JavaScript Closures and IIFEs Work
1.30 GEEK