Discussion: The Fun-ction
Execute the code to understand the output and gain insights into the variable’s scope and various forms of syntax we can use for IIFEs in JavaScript.
We'll cover the following...
We'll cover the following...
Verifying the output
Now, it’s time to execute the code and observe the output.
Javascript (babel-node-es2024)
!function() {const name = "john";const age = 20;}();const capitalizedName = name[0].toUpperCase() + name.slice(1);console.log(capitalizedName);
Understanding the output
The problem in this code is that name has what we call function scope, meaning it’s accessible only within that function. So, if we attempt to use the value of name out of the function, we’ll encounter a reference error because name is undefined in the outer scope.
Immediately invoked function expression (IIFE)
The function in this puzzle is known as an immediately invoked function expression (IIFE) ...