Mastering JavaScript: Unraveling the Power of Web Development
Scope
Scope means variable access. What variable do I have access to when a code is running? In Javascript by default, you’re always in the root scope i.e. the window scope. The scope is simply a box with a boundary for variables, functions, and objects. These boundaries put restrictions on variables and determine whether you have access to the variable or not. It limits the visibility or availability of a variable to the other parts of the code. You must have a clear understanding of this concept because it helps you to separate logic in your code and also improves readability. A scope can be defined in two ways –
Local Scope allows access to everything within the boundaries (inside the box)
Global Scope is everything outside the boundaries (outside the box). A global scope can not access a variable defined in the local scope because it is enclosed from the outer world, except if you return it.
Block Scope is everything inside the boundaries but it works only for var and const keywords. It does not work with the var keyword.
More about block scope
Example: The code given below will give you an error because “name” is defined within the boundary (local scope) of the showName() function. You can not have access to this variable outside the function.
NOTE: The code below shows an error due to a typo in the function call, causing an error before the intended scoping error is raised by the console.log call.
function showName(){
let name - "PrasoonAbhinaw";
}
showname();
console.log(name);
Output: Uncaught ReferenceError: showname is not defined at :4:1
Block Scope example: Below code will give error as "a" is not known outside fun()
function fun() {
let a = 10;
console.log(a);
}
console.log(a);
Output: Uncaught ReferenceError: a is not defined at :5:17
Example: The below example will not throw an error and give 20 20 as output as block scope does not work with var.
let a = 10;
function fun() {
let a = 20;
console.log(a);
}
console.log(a);function showName(){
let name = "PrasoonAbhinaw";
console.log(name);
}
showName();
IIFE (Immediately Invoked Function Expression):
As the name suggests IIFE is a function in Javascript which immediately invoked and executed as soon as it is defined. Variables declared within the IIFE cannot be accessed by the outside world and this way you can avoid the global scope from getting polluted. So the primary reason to use IIFE is to immediately execute the code and obtain data privacy.
Example:
let paintColor = 'red'
const paint = (() => {
return {
changeColorToBlue: () => {
paintcolor: 'Blue': return paintColor;
},
changeColorToGreen: () => {
paintColor: 'Green';
return paintColor;
}
}
})();
console.1og(
paint.changeColorToBlue()
);
Output: Red
Converting Functions to IIFEs
As we have already seen what an IIFE is and how its syntaxial form can be broken down to make more sense, We can convert a regular function into an IIFE following only two steps as follows.
Given any regular function definition, wrap the definition within a closed pair of parentheses, this will create your Function Expression.
Lastly, add another pair of parentheses and a semicolon to mark the end of the statement, and you have converted your regular Function into an IIFE.
Example:
// Regular Function.
function Greet() {
console.log("Welcome to Engineering world!");
};
// Execution of Regular Function.
Greet();
// IIFE creation and execution.
(function() {
console.log("Welcome to Engineering Life");
})();
Output:
Welcome to Engineering world!
Welcome to Engineering Life!
Note:
IIFEs have their own scope i.e. the variables you declare in the Function Expression will not be available outside the function.
Similarly to other functions IIFEs can also be named or anonymous, but even if an IIFE does have a name it is impossible to refer/invoke it.
IIFEs can also have parameters. For example,
Use Case of IIFE
Avoid polluting the global namespace
To create closures
Avoid conflict of variable names between libraries and programs.
IIFE is used to create private and public variables and methods
It is used to execute the async and await function
It is used in JQuery Library
It is used to work with require function
Thanks for your time and I hope you enjoyed this article!
Subscribe to my newsletter
Read articles from Prasoon Abhinaw directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Prasoon Abhinaw
Prasoon Abhinaw
I am a passionate software engineer with over 16 years of hands-on experience in the tech industry. On this blog, I aim to share my expertise, insights, and love for engineering with all of you. Whether you're a seasoned developer or just starting your journey in the world of code, this blog is here to empower you and elevate your skills. What to Expect: Expect a diverse range of content, including in-depth tutorials, coding challenges, software development tips, algorithmic insights, tech reviews, and discussions on the latest trends in the tech sphere. We'll explore various programming languages, design patterns, data structures, and best practices to help you become a more proficient engineer.