One unique thing that differentiates your Javascript series with rest all is the way you teach us best practices & important points with good examples rather than following the common procedure of just covering the basics which everyone does. Sharing important interview questions too
Immediately Invoked Function Expressions (IIFE): the secret sauce for encapsulating code and maintaining a clean global scope. In this video, you'll uncover the power of IIFEs and how they can enhance code organization, protect variables, and prevent naming collisions. Whether you're a seasoned developer or just starting out, understanding and utilizing IIFEs will level up your JavaScript skills. Get ready to dive into this transformative concept and supercharge your coding prowess!
I took an Udemy Course wherein IIFE was explained for about 30-35 mins but I didn't understood a single word. Here things are much simpler to understand. Thank You Hitesh Sir!
(function() { console.log("Hello, Chai or code !"); })(); example: Tumne function banaya (function() { ... }) Aur phir isko turant call kiya () Yeh kaam kuch is tarah hota hai jaise tumne function ko likha aur pehle se hi keh diya ke “jaldi se chalo”! Iska fayda yeh hota hai ke tumhara function turant chalega aur apne kaam ke baad khatam ho jayega.
I am profoundly awestruck and deeply appreciative of my teacher's (sir hitesh chodhary) exceptional ability to delve into the intricate nuances of JavaScript language concepts, elevating my comprehension to remarkable heights and leaving me utterly inspired.
I am absolutely captivated by the way you masterfully unraveled the intricacies of JavaScript language concepts, infusing each lesson with a sense of wonder and leaving me both spellbound and incredibly grateful.
SUMMARY : 1. IIFE is a function which immediately executes after it's creation . It is wriiten as one parentheses for wrapping the function and other for execution ()(); 2. Variables defined inside an IIFE are not accessible from outside its scope which helps to avoid conflicts with other variables or functions (global scope pollution). Means IIFE keeps variables and functions private in it. 3. IIFE written with function name is named IIFE and not with name are unnamed/anonymous. 4.We can use parameter inside first parentheses. 5. To write two or multiple IIFE one should be end with semicolon ;
sir you are rocking I missed my js class and i think thats great because I found you and learn more technical with ans than lecture;s without explanation theory. In earlier after py i hate js but after your lecture i m enjoying and writing so many codes in day and committing git too, thank you so much sir btw, current time is 12: 39 CST and I love it at midnight
Full code + notes + Explanatory comment // Avoiding Global Scope Pollution: // Variables declared inside the IIFE are not added to the global scope. This helps in preventing naming conflicts with other scripts and libraries. // Encapsulation: // It allows encapsulation of variables. Variables declared inside the IIFE are not accessible from the outside, providing a level of privacy. // Isolation: // It helps in isolating code. Variables declared inside the IIFE do not interfere with variables in the outer scope, and vice versa. // Module Pattern: // IIFE is often used in creating a module pattern, allowing the creation of private and public methods within the same scope. // Avoiding Hoisting Issues: // By using a function expression, you avoid hoisting issues that can occur with function declarations. // Immediately Invoked Function Expression (IIFE) - Named IIFE (function chai() { console.log(`DB connected`); })(); // Output: DB connected // If two IIFE are used, it's a good practice to end each with a semicolon to avoid potential issues. // Immediately Invoked Function Expression (IIFE) - Unnamed IIFE ( (name) => { console.log(`DB connected ${name}`); } )('Postgres'); // Output: DB connected Postgres // Explanation: // - The first IIFE is named 'chai' and logs "DB connected" immediately when the script runs. // - The second IIFE is unnamed and takes a parameter 'name', followed by the provided name ('Postgres'). // - Both IIFE syntaxes are valid, and the use of parentheses around the function helps to indicate that it's a function expression being invoked immediately. // Note: Ending IIFE with semicolons is especially important when you are combining multiple JavaScript files into one, to prevent unexpected issues due to automatic semicolon insertion.
We need IIFE to deal with two things: 1. To prevent any pollution to the global scope from the values inside our function - now, this holds true when working with the oudated var keyword or in instances where you mistakenly declare the functions and variables in the global scope instead of inside the intended function. If you take care of both these things, IIFE’s are not a strict requirement to prevent polluting the global scope. 2. To call a function immediately - there can be instances where we need to immediately invoke a function but there can be other ways as well to immediately invoke the functions other than IIFEs. Overall , IIFEs are a good code practice to prevent any potential pollution problems in cases we are exporting our code to other files and also the code looks clean
Absolutely right sir, these videos makes us confident. Because of this I can say, yes I know js from scratch 😊. Thanks alot sir.... Big appreciation from my side #madhubani, Bihar
I don't know what is IIFE apki backend ki series dekh rha tha abhi tab main socha IIFE dekh lo phr ap ki ye video bhi dhondh li ❤ Great Sir, Kmall ka teaching level hai 🔥🔥
IIFEs are used in JavaScript for several reasons: Prevent global pollution: Variables and functions inside stay private, avoiding conflicts with other code. Create modules: Encapsulate code to organize and isolate functionality. Run code immediately: Useful for initialization tasks or ensuring execution on page load. Control `this` behavior: Bind `this` explicitly within the IIFE for specific scenarios. Think of IIFEs as self-contained bubbles for your code, keeping it tidy and organized!
A very simple example given below // IIFE // example of named iife function (function HW(){ console.log("Hello world") })(); // example of unamed Iife function (() =>{ console.log("Hello Universe") } )();
00:02 IF Immediately Invoked Function Expression in JavaScript 00:57 Separate scopes are created to avoid pollution from the global scope 01:50 Writing the function with the 'if' statement is easy but it is important to invoke the function immediately. 02:43 Understanding the execution of functions and its impact on global scope pollution. 03:37 Function written in the manner of Ara function causing an error 04:41 Use semicolons to properly end lines of code 05:34 Passing arguments to a function in JavaScript 06:33 Naming conventions in IF statements
00:02 IF Immediately Invoked Function Expression in JavaScript 00:57 Separate scopes are created to avoid pollution from the global scope 01:50 Writing the function with the 'if' statement is easy but it is important to invoke the function immediately. 02:43 Understanding the execution of functions and its impact on global scope pollution. 03:37 Function written in the manner of Ara function causing an error 04:41 Use semicolons to properly end lines of code 05:34 Passing arguments to a function in JavaScript 06:33 Naming conventions in IF statements Crafted by Merlin AI.
If someone's IIFE not working try using this ; (function chai() { console.log(" DB Connected ") })(); It is because Nodejs environment concatenate the previous line of code with the IIFE
👆🏼 Quetion: Can an IIFE have a return value? No in normal case. But if someone stores it in a valiable it can be keept and reuse it. const result = (function() { return 10; })(); console.log(result); (totally out of curiosity banged my head init this and i found this, thought to share with people)
Such a content full learning .. #"full knowledge wasool "😊 this channel is so resourceful, if anybody wnna deep dive with Mern must go through this series and channel 🎉😊
In light of your exceptional teaching, could you please point me towards the next enthralling video series that delves into the realm of Next.js ,React and typescript and database etc ? Your insights have been instrumental in shaping my understanding, and I'm genuinely excited to embark on this next phase of learning under your esteemed guidance.
This is how global scope gets polluted var ex = "nagin"; // assume it is imported from library or written by other developer // some thousand line code if (true) { // we wrote this var ex = "good one"; // it broke the code below by modifying variable above console.log(ex); } // some thousand line code console.log(ex); // some other developer coded this and this is how IIFE prevents it var ex = "nagin"; // assume it is imported from library // some thousand line code (function () { if (true) { // we wrote this var ex = "good one"; // it broke the code below by modifying variable above console.log(ex); } })(); // some thousand line code console.log(ex); // some other developer coded this A normal function can also do the same job but if we don't need that function again, we usually use IIFE.
Sir, how IIFE and normal function different in case of polluting globle scope, as far as i know, i think normal function are aslo avoid polluting globle scope, so how can we differtiate IIFE and normal function in case of polluting globle scope?
Sir it would have been better if aapne global variable declare krke uski value ko manipulate krke dikhaya hota inside the iife, that is something we dont want to happen if we're having the same variable name as of initially declared global variable ! Taaki aage jaakr joh global variable hai uski value change na ho... So in order to achieve that we will use var or let inside the iife with our variable name...
// Immediately Invoked Function Expressions (IIFE) // IIFE = the secret sauce for encapsulating code and maintaining a clean global scope. // They can enhance code organization, protect variables, and prevent naming collisions. // It used for imediate invokation of function, we don't want pollution from global scope at all. // used --> while some time we want to coonect our DB and get that message. // ()() --> 1.() => For function defination, 2.() => For function call. (function chai(){ // named IIFE console.log(`DB CONNECTED`); // DB CONNECTED })(); // If you don't keep ";" Then this will give an error and the next function will not be executed. // Unnamed/simple IIFE with parameters and arguments ( (name) => { console.log(`DB CONNECTED TWO ${name}`); //DB CONNECTED TWO Krishnakunj } )('Krishnakunj')
arrow functions with implicit return needs to be terminated with a semicolon too; faced a case where I defined an arrow function with implicit return and then defined an IIFE. but the IIFE didn't got invoked unless I terminated the arrow function. Hope that helps someone.
One unique thing that differentiates your Javascript series with rest all is the way you teach us best practices & important points with good examples rather than following the common procedure of just covering the basics which everyone does.
Sharing important interview questions too
Immediately Invoked Function Expressions (IIFE): the secret sauce for encapsulating code and maintaining a clean global scope. In this video, you'll uncover the power of IIFEs and how they can enhance code organization, protect variables, and prevent naming collisions. Whether you're a seasoned developer or just starting out, understanding and utilizing IIFEs will level up your JavaScript skills. Get ready to dive into this transformative concept and supercharge your coding prowess!
Hanji, suntehi mann pura positive energy se bhar jata ha aur coding karneka mann karta ha. Thanks sir for this best JavaScript series.
Aap ka teaching ka andaz bohot acha laga. Aap ki wajah se JavaScript seekhna asaan aur interesting ho gaya hai. Shukriya!
Never new this is called IIFE, though know this is an another way to call an function.. Thank you sir for such detailed videos.
sir kamal kr ty ho ap
bht achay sy or behtareen andaz may samjhaya ap nay
big respect big respect for you
Thanks
I took an Udemy Course wherein IIFE was explained for about 30-35 mins but I didn't understood a single word. Here things are much simpler to understand. Thank You Hitesh Sir!
lol same
Awesome Way of teaching. By far best javaScript content on youtube.
Thanks a lot
AWESOME SIR YOUR WAY OF TEACHING MAKES U TOTALLY DIFFERENT FROM OTHERS .THANKU SO MUCH SIR FOR UPLOADING SUCH A QUALITY CONTENT IN FREE
Best Lecture, understood everything, Thank you sir!
(function() {
console.log("Hello, Chai or code !");
})();
example:
Tumne function banaya (function() { ... })
Aur phir isko turant call kiya ()
Yeh kaam kuch is tarah hota hai jaise tumne function ko likha aur pehle se hi keh diya ke “jaldi se chalo”!
Iska fayda yeh hota hai ke tumhara function turant chalega aur apne kaam ke baad khatam ho jayega.
I am profoundly awestruck and deeply appreciative of my teacher's (sir hitesh chodhary) exceptional ability to delve into the intricate nuances of JavaScript language concepts, elevating my comprehension to remarkable heights and leaving me utterly inspired.
Radhe Radhe ❤❤
Thankyou sir for the amazing lecture.
Completely get it what's IIFE and most important is why we use it in real world scenario. Love your way of explaning topics.
I am absolutely captivated by the way you masterfully unraveled the intricacies of JavaScript language concepts, infusing each lesson with a sense of wonder and leaving me both spellbound and incredibly grateful.
Ohh bhai 😂
Ohh bhai 😂
SUMMARY :
1. IIFE is a function which immediately executes after it's creation . It is wriiten as one parentheses for wrapping the function and other for execution ()();
2. Variables defined inside an IIFE are not accessible from outside its scope which helps to avoid conflicts with other variables or functions (global scope pollution). Means IIFE keeps variables and functions private in it.
3. IIFE written with function name is named IIFE and not with name are unnamed/anonymous.
4.We can use parameter inside first parentheses.
5. To write two or multiple IIFE one should be end with semicolon ;
Your teaching skills are top notch, Thankyou for this great video.
You are very welcome
Hello sir hitesh im shoaib from karachi pakistan im learning javascript from your playlist its a awesome playlist thank you so much for this series
Amazing concepts, I am learning a lot from your channel
sir you are rocking I missed my js class and i think thats great because I found you and learn more technical with ans than lecture;s without explanation theory.
In earlier after py i hate js but after your lecture i m enjoying and writing so many codes in day and committing git too,
thank you so much sir
btw, current time is 12: 39 CST and I love it at midnight
Full code + notes + Explanatory comment
// Avoiding Global Scope Pollution:
// Variables declared inside the IIFE are not added to the global scope. This helps in preventing naming conflicts with other scripts and libraries.
// Encapsulation:
// It allows encapsulation of variables. Variables declared inside the IIFE are not accessible from the outside, providing a level of privacy.
// Isolation:
// It helps in isolating code. Variables declared inside the IIFE do not interfere with variables in the outer scope, and vice versa.
// Module Pattern:
// IIFE is often used in creating a module pattern, allowing the creation of private and public methods within the same scope.
// Avoiding Hoisting Issues:
// By using a function expression, you avoid hoisting issues that can occur with function declarations.
// Immediately Invoked Function Expression (IIFE) - Named IIFE
(function chai() {
console.log(`DB connected`);
})();
// Output: DB connected
// If two IIFE are used, it's a good practice to end each with a semicolon to avoid potential issues.
// Immediately Invoked Function Expression (IIFE) - Unnamed IIFE
(
(name) => {
console.log(`DB connected ${name}`);
}
)('Postgres');
// Output: DB connected Postgres
// Explanation:
// - The first IIFE is named 'chai' and logs "DB connected" immediately when the script runs.
// - The second IIFE is unnamed and takes a parameter 'name', followed by the provided name ('Postgres').
// - Both IIFE syntaxes are valid, and the use of parentheses around the function helps to indicate that it's a function expression being invoked immediately.
// Note: Ending IIFE with semicolons is especially important when you are combining multiple JavaScript files into one, to prevent unexpected issues due to automatic semicolon insertion.
thanks
great bro
Unbelievable content! Hats Off to Hitesh Sir 🙏🙏🙏🙏❤❤
Thanks 🙏😊☕️
Sir your JavaScript playlist is top notch. Explaining the concepts very well and very easily.❤❤❤
Thanks a ton 😊🙏
We need IIFE to deal with two things:
1. To prevent any pollution to the global scope from the values inside our function - now, this holds true when working with the oudated var keyword or in instances where you mistakenly declare the functions and variables in the global scope instead of inside the intended function. If you take care of both these things, IIFE’s are not a strict requirement to prevent polluting the global scope.
2. To call a function immediately - there can be instances where we need to immediately invoke a function but there can be other ways as well to immediately invoke the functions other than IIFEs.
Overall , IIFEs are a good code practice to prevent any potential pollution problems in cases we are exporting our code to other files and also the code looks clean
Absolutely right sir, these videos makes us confident. Because of this I can say, yes I know js from scratch 😊. Thanks alot sir.... Big appreciation from my side #madhubani, Bihar
Sir you are the best teacher.
I have learnt a lot of js because of you.
Thank you very much sir 😍
इस awesome content के लिए -
धन्यवाद हितेश
I was sick the whole week , now I'm back again and will complete the whole playlist IA.
It's a better practice to use ; after every expression ❤
"Master IIFEs with this clear, concise tutorial! Ideal for JavaScript learners. #chai" - 9 words.
best and simple explanation love from nepal ,aab ma chai pine laga hu ma
sir ek he dil h kitni baar jitoge ❤❤
Thanks a lot Hitesh for such a wonderful explanation
I don't know what is IIFE apki backend ki series dekh rha tha abhi tab main socha IIFE dekh lo phr ap ki ye video bhi dhondh li ❤
Great Sir, Kmall ka teaching level hai 🔥🔥
Sir 🙏🙏🙏🙏🙏🙏ji bot achi chai banai hai maza aagya ❤
Really learning a lot from you, sir! Thanks for providing us this learning for free! 🙌🏻
You always more than expectation ❤
I be like itna depth me kon teach h
Vo bhi chai ke sath
Thanks, your video is really time-saving!
Thank you so much for this simple explanation❤
Super duper work Hitesh bhai
Sir border Paar Se Buht Sara Piyar Apke Liye...
IIFEs are used in JavaScript for several reasons:
Prevent global pollution: Variables and functions inside stay private, avoiding conflicts with other code.
Create modules: Encapsulate code to organize and isolate functionality.
Run code immediately: Useful for initialization tasks or ensuring execution on page load.
Control `this` behavior: Bind `this` explicitly within the IIFE for specific scenarios.
Think of IIFEs as self-contained bubbles for your code, keeping it tidy and organized!
"Chai aur Code, you're the mentor every JavaScript learner dreams of. Phenomenal content!"
Wow i like your teaching style bhaiya!!
3:00 That's cooooool 🫨
First of all thank you sir to giving such a practical content to us please make Interview Base video on reacts and JavaScript 💌🙏
PROVIDING EXTRA KNOWLEGE IS YOUR KEY FEATURE
A very simple example given below
// IIFE
// example of named iife function
(function HW(){
console.log("Hello world")
})();
// example of unamed Iife function
(() =>{
console.log("Hello Universe")
} )();
00:02 IF Immediately Invoked Function Expression in JavaScript
00:57 Separate scopes are created to avoid pollution from the global scope
01:50 Writing the function with the 'if' statement is easy but it is important to invoke the function immediately.
02:43 Understanding the execution of functions and its impact on global scope pollution.
03:37 Function written in the manner of Ara function causing an error
04:41 Use semicolons to properly end lines of code
05:34 Passing arguments to a function in JavaScript
06:33 Naming conventions in IF statements
Beautifully Explained
Lub you Sir g . #RUclips run this comment as IIfe function 😁😁😁. And donot forgot to use ; at the end of IIfe function
00:02 IF Immediately Invoked Function Expression in JavaScript
00:57 Separate scopes are created to avoid pollution from the global scope
01:50 Writing the function with the 'if' statement is easy but it is important to invoke the function immediately.
02:43 Understanding the execution of functions and its impact on global scope pollution.
03:37 Function written in the manner of Ara function causing an error
04:41 Use semicolons to properly end lines of code
05:34 Passing arguments to a function in JavaScript
06:33 Naming conventions in IF statements
Crafted by Merlin AI.
If someone's IIFE not working try using this
; (function chai()
{
console.log(" DB Connected ")
})();
It is because Nodejs environment concatenate the previous line of code with the IIFE
👆🏼 Quetion: Can an IIFE have a return value? No in normal case. But if someone stores it in a valiable it can be keept and reuse it.
const result = (function() {
return 10;
})();
console.log(result);
(totally out of curiosity banged my head init this and i found this, thought to share with people)
A very well explained , thank you sir
Such a content full learning .. #"full knowledge wasool "😊 this channel is so resourceful, if anybody wnna deep dive with Mern must go through this series and channel 🎉😊
Thanks a ton
Beautifully explained!
bade bhaiya dhanyavaad apka
In light of your exceptional teaching, could you please point me towards the next enthralling video series that delves into the realm of Next.js ,React and typescript and database etc ? Your insights have been instrumental in shaping my understanding, and I'm genuinely excited to embark on this next phase of learning under your esteemed guidance.
Check out my English Channel, Hitesh Choudhary.
Such topics are covered there
kaafi majedar tha ye video
Nice explanation ❤
yar ap love ho
Thank you for that 2nd IIFE.
thank you sir maja a gya great explanation and so intresting
So nice of you 😊
Hi sir thanks for explaining such deep concepts.Waiting for react native episodes.Thanks in advance
Immediately invoked function expressions😊
Thanks A Lot Sir ❤❤
This is how global scope gets polluted
var ex = "nagin"; // assume it is imported from library or written by other developer
// some thousand line code
if (true) { // we wrote this
var ex = "good one"; // it broke the code below by modifying variable above
console.log(ex);
}
// some thousand line code
console.log(ex); // some other developer coded this
and this is how IIFE prevents it
var ex = "nagin"; // assume it is imported from library
// some thousand line code
(function () {
if (true) {
// we wrote this
var ex = "good one"; // it broke the code below by modifying variable above
console.log(ex);
}
})();
// some thousand line code
console.log(ex); // some other developer coded this
A normal function can also do the same job but if we don't need that function again, we usually use IIFE.
Love the session
GREAT PLAYLIST GOING ON ...
Semicolon after IIFE
We can also pass arguments to IIFE
Named IIFE are IIFE function with name
Great content!
Sir g thusi great ❤
Very nice content sir 💯💯💯💯
Sir, how IIFE and normal function different in case of polluting globle scope, as far as i know, i think normal function are aslo avoid polluting globle scope, so how can we differtiate IIFE and normal function in case of polluting globle scope?
Sir it would have been better if aapne global variable declare krke uski value ko manipulate krke dikhaya hota inside the iife, that is something we dont want to happen if we're having the same variable name as of initially declared global variable ! Taaki aage jaakr joh global variable hai uski value change na ho...
So in order to achieve that we will use var or let inside the iife with our variable name...
Great lecture
Thank you sir❤️
thanks,great one
poora clear hogaya, bach gaya interview
full clear hoga interview
Thank you so much sir❤❤❤
Global scope mein kya pollution ho sakte hai , any practical scenario?
Thank You Sir
// Immediately Invoked Function Expressions (IIFE)
// IIFE = the secret sauce for encapsulating code and maintaining a clean global scope.
// They can enhance code organization, protect variables, and prevent naming collisions.
// It used for imediate invokation of function, we don't want pollution from global scope at all.
// used --> while some time we want to coonect our DB and get that message.
// ()() --> 1.() => For function defination, 2.() => For function call.
(function chai(){
// named IIFE
console.log(`DB CONNECTED`); // DB CONNECTED
})();
// If you don't keep ";" Then this will give an error and the next function will not be executed.
// Unnamed/simple IIFE with parameters and arguments
( (name) => {
console.log(`DB CONNECTED TWO ${name}`); //DB CONNECTED TWO Krishnakunj
} )('Krishnakunj')
thank you sir
iife used to protect function from global pollution
Thank you
Waiting for next lecture...❤
Great One!
learnt new things
This was asked in TCS ninja interview
@chaiaurcode - If we return some value in IIFE execution then where it will get stored?
Or how we can store that return value ?
arrow functions with implicit return needs to be terminated with a semicolon too;
faced a case where I defined an arrow function with implicit return and then defined an IIFE. but the IIFE didn't got invoked unless I terminated the arrow function. Hope that helps someone.
thank you hitesh
Interesting topic
Thanks Sir!
hitesh sir op
thanks sir
what an explanation bhai!!
What is global scope pollution here ??