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.
Verifying the output
Now, it’s time to execute the code and observe the output.
Press + to interact
!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 ...