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!
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.
(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 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
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.
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
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
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.
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
👆🏼 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)
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 🔥🔥
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 🎉😊
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.
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") } )();
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
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!
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...
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?
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.
I have created Global variable const x and assign value 5 and then created my iffe function and try to access that global variable but it is accessible in iffe function ? why ? you said sir it prevent it
Sir aik question hy woh yh k me ik CA finalist student ho pakistan sy coding or tech me bohot interest tha par kisi waja sy usko pursue ni kr paya pr ab JS seekh ra ho q k maza a ra hy is course me. Janna yh chahta ho iska use case kia ho skta hy mery lia
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.
But when I am giving arrow function like this (let iife = () => { console.log("db connected agains"); })(); it shows me an error so why this error is coming .
(let sum = function(){ console.log(`hassan`); return sum })() IIFE use krty hovy hm variable mien value store ku nhi krwa skty ????????????????????????????????????
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
Aap ka teaching ka andaz bohot acha laga. Aap ki wajah se JavaScript seekhna asaan aur interesting ho gaya hai. Shukriya!
sir kamal kr ty ho ap
bht achay sy or behtareen andaz may samjhaya ap nay
big respect big respect for you
Thanks
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.
Never new this is called IIFE, though know this is an another way to call an function.. Thank you sir for such detailed videos.
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!
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
Radhe Radhe ❤❤
Thankyou sir for the amazing lecture.
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.
(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 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 😂
Amazing concepts, I am learning a lot from your channel
Completely get it what's IIFE and most important is why we use it in real world scenario. Love your way of explaning topics.
Sir you are the best teacher.
I have learnt a lot of js because of you.
Thank you very much sir 😍
Your teaching skills are top notch, Thankyou for this great video.
You are very welcome
Sir your JavaScript playlist is top notch. Explaining the concepts very well and very easily.❤❤❤
Thanks a ton 😊🙏
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
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
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.
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
best and simple explanation love from nepal ,aab ma chai pine laga hu ma
Unbelievable content! Hats Off to Hitesh Sir 🙏🙏🙏🙏❤❤
Thanks 🙏😊☕️
I was sick the whole week , now I'm back again and will complete the whole playlist IA.
इस awesome content के लिए -
धन्यवाद हितेश
Sir 🙏🙏🙏🙏🙏🙏ji bot achi chai banai hai maza aagya ❤
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
Thanks a lot Hitesh for such a wonderful explanation
Wow i like your teaching style bhaiya!!
It's a better practice to use ; after every expression ❤
Thank you so much for this simple explanation❤
First of all thank you sir to giving such a practical content to us please make Interview Base video on reacts and JavaScript 💌🙏
sir ek he dil h kitni baar jitoge ❤❤
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
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
Super duper work Hitesh bhai
Thanks, your video is really time-saving!
👆🏼 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)
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 🔥🔥
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
Sir border Paar Se Buht Sara Piyar Apke Liye...
Really learning a lot from you, sir! Thanks for providing us this learning for free! 🙌🏻
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
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")
} )();
Beautifully Explained
"Master IIFEs with this clear, concise tutorial! Ideal for JavaScript learners. #chai" - 9 words.
Beautifully explained!
A very well explained , thank you sir
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
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!
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...
You always more than expectation ❤
I be like itna depth me kon teach h
Vo bhi chai ke sath
PROVIDING EXTRA KNOWLEGE IS YOUR KEY FEATURE
bade bhaiya dhanyavaad apka
Nice explanation ❤
thank you sir maja a gya great explanation and so intresting
So nice of you 😊
Lub you Sir g . #RUclips run this comment as IIfe function 😁😁😁. And donot forgot to use ; at the end of IIfe function
3:00 That's cooooool 🫨
"Chai aur Code, you're the mentor every JavaScript learner dreams of. Phenomenal content!"
Semicolon after IIFE
We can also pass arguments to IIFE
Named IIFE are IIFE function with name
kaafi majedar tha ye video
Thank you for that 2nd IIFE.
Love the session
Great content!
Thanks A Lot 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?
yar ap love ho
Thank you sir !!
Hi sir thanks for explaining such deep concepts.Waiting for react native episodes.Thanks in advance
Sir g thusi great ❤
thanks,great one
Great lecture
GREAT PLAYLIST GOING ON ...
Very nice content sir 💯💯💯💯
Thank you so much sir❤❤❤
Global scope mein kya pollution ho sakte hai , any practical scenario?
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 Sir
Namaste sir, now I got to why my compiler shows error while coding two iife before subscribe you 🎉
Great One!
Immediately invoked function expressions😊
(function sum (num1,num2) {
num1 + num2
})(5,4);
console.log(sum(5,8));
Can't i use iife functions after they are declared
Thank you
sir, can't we pass object inside a function when we are dealing with IIFE?
I have created Global variable const x and assign value 5
and then created my iffe function and try to access that global variable but it is accessible in iffe function ?
why ?
you said sir it prevent it
Sir front-end or back end developer ka future scope keya hai sir 🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔
learnt new things
Sir aik question hy woh yh k me ik CA finalist student ho pakistan sy coding or tech me bohot interest tha par kisi waja sy usko pursue ni kr paya pr ab JS seekh ra ho q k maza a ra hy is course me. Janna yh chahta ho iska use case kia ho skta hy mery lia
what an explanation bhai!!
thank you hitesh
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.
what is tge mening of global pollute sir 🤔 samjha nahi kaisey pollute kar dega
But when I am giving arrow function like this
(let iife = () => {
console.log("db connected agains");
})();
it shows me an error so why this error is coming .
Thanks Sir!
@chaiaurcode - If we return some value in IIFE execution then where it will get stored?
Or how we can store that return value ?
(let sum = function(){
console.log(`hassan`);
return sum
})() IIFE use krty hovy hm variable mien value store ku nhi krwa skty ????????????????????????????????????
Interesting topic