Immediately Invoked Function Expressions (IIFE) | JavaScript 🔥 | Lecture 127
Summary
TLDRThe video script delves into Immediately Invoked Function Expressions (IIFEs), a JavaScript pattern that allows executing a function immediately after its definition. IIFEs create a private scope, enabling data encapsulation and preventing accidental variable overwrites. While IIFEs were historically used for this purpose, modern JavaScript allows creating blocks with `let` and `const` for data privacy, reducing the need for IIFEs. However, IIFEs remain useful when a function needs to execute only once, as they serve that purpose elegantly. The script explores the rationale, syntax, and use cases of IIFEs, providing a comprehensive understanding of this intriguing JavaScript concept.
Takeaways
- 👉 Immediately Invoked Function Expressions (IIFEs) are functions that are executed immediately after being defined, without needing to be called later.
- 🔑 IIFEs are useful when you need a function to run only once and then disappear, for example, with async/await.
- 🌐 IIFEs create a new scope, allowing data encapsulation and privacy, which are important concepts in programming.
- 🔒 Data encapsulation and privacy help protect variables from being accidentally overwritten by other parts of the program or external scripts/libraries.
- 🆚 In modern JavaScript, using blocks with let or const can achieve data privacy without the need for IIFEs, unless you need to use var.
- ➡️ IIFEs are still useful if you specifically need to execute a function just once, even with modern JavaScript.
- 📝 IIFEs can be created with a normal function expression or an arrow function expression, wrapped in parentheses and immediately invoked.
- 🔄 While IIFEs were a popular pattern in older JavaScript, they are not as commonly used now due to the availability of blocks and let/const.
- 🧠 Understanding scopes and data encapsulation is crucial for writing clean and maintainable code.
- 🚀 IIFEs provide a way to execute a function immediately while also creating a new scope for data privacy and encapsulation.
Q & A
What is an Immediately Invoked Function Expression (IIFE) in JavaScript?
-An IIFE is a JavaScript function that runs as soon as it is defined. It is a design pattern used to execute a function immediately without saving it or having the ability to execute it again.
Why might we need to use an IIFE in JavaScript?
-We might use an IIFE for code that only needs to run once and then never again, such as setting up an initial state, or to immediately execute setup code in a scope that doesn't pollute the global namespace.
How do you create an IIFE?
-You create an IIFE by writing a function expression and immediately invoking it. This is done by wrapping the function in parentheses and adding another pair of parentheses at the end to call it.
Why does wrapping a function in parentheses turn it into an expression in JavaScript?
-Wrapping a function in parentheses in JavaScript tricks the parser into treating it as an expression rather than a statement. This allows the function to be immediately invoked without throwing an error.
Can arrow functions be used as IIFEs?
-Yes, arrow functions can also be used as IIFEs. The syntax is similar to using a regular function expression, where the arrow function is enclosed in parentheses and immediately invoked.
What is the purpose of using IIFEs for variable scope?
-IIFEs are used to create a new scope for variables, ensuring they are encapsulated and private within the function. This prevents the variables from being accessible or overwritten from the outside scope, enhancing data privacy and security.
How have ES6 features like let and const changed the use of IIFEs for scoping?
-With ES6, the introduction of `let` and `const` allows for block scoping, which reduces the need for IIFEs to create new scopes for data privacy. Variables declared with `let` or `const` are confined to the block scope, not requiring an IIFE for the same purpose.
Are IIFEs still relevant in modern JavaScript development?
-While the need for IIFEs for scoping has diminished with ES6 block scoping, they remain relevant for executing functions exactly once, especially in situations where an isolated scope is necessary without polluting the global namespace.
What is data encapsulation, and how do IIFEs contribute to it?
-Data encapsulation is a principle of hiding the internal state and functionality of a component, only exposing what is necessary. IIFEs contribute to data encapsulation by creating a private scope for variables and functions, preventing external access or modification.
Why is it important to hide variables using scopes in JavaScript?
-Hiding variables using scopes is important to prevent them from being accidentally overwritten by other parts of the program or external scripts. It ensures data privacy and integrity, and is a key aspect of secure and reliable programming practices.
Outlines
🔍 Immediately Invoked Function Expressions (IIFEs)
This paragraph introduces the concept of Immediately Invoked Function Expressions (IIFEs) in JavaScript. IIFEs are functions that are executed immediately after they are defined, without being assigned to a variable. This technique is useful when you need a function to run only once and then never again, such as for encapsulating data or running initialization code. The paragraph explains how to create an IIFE using both regular function expressions and arrow functions, and demonstrates their execution with examples.
🔒 Data Encapsulation and Privacy with IIFEs
This paragraph discusses the importance of data encapsulation and privacy in programming, and how IIFEs can be used to achieve this. It explains that functions create their own scope, and variables defined within a function scope are private and cannot be accessed from the outer scope (global scope). This concept of data privacy is crucial to prevent accidental overwriting of variables by other parts of the program or external scripts/libraries. The paragraph also mentions that modern JavaScript has introduced block-level scoping with `let` and `const`, which provides an alternative way to create private scopes without the need for IIFEs. However, IIFEs are still useful when you need to execute a function only once.
Mindmap
Keywords
💡Immediately Invoked Function Expression (IIFE)
💡Scope
💡Data Encapsulation
💡Data Privacy
💡Block Scope
💡Function Expression
💡Arrow Function
💡Global Scope
💡Scope Chain
💡Variable Declaration
Highlights
Introduction to Immediately Invoked Function Expressions (IIFEs) in JavaScript.
IIFEs are used for functions that are only executed once and then never again.
IIFEs are essential for techniques like async/await.
Creating a function and executing it only once without saving it.
Using parentheses to trick JavaScript into treating the function as an expression.
The function inside the parentheses can be immediately called.
IIFEs can be written using both function expressions and arrow functions.
Functions create scopes in JavaScript, which is crucial for data privacy.
Variables within a function's scope are private and encapsulated.
Data encapsulation and privacy are important programming concepts.
IIFEs were invented to protect variables and create private scopes.
In ES6, let and const create their own scope within a block, reducing the need for IIFEs for scope creation.
Modern JavaScript uses blocks for data privacy instead of IIFEs.
IIFEs are still relevant for executing a function exactly once.
IIFEs are a pattern developed by developers rather than a built-in JavaScript feature.
Transcripts
Our next topic is something called,
Immediately Invoked Function Expressions.
So let's take a look at what they are.
So sometimes in JavaScript,
we need a function that is only executed once.
And then never again.
So basically a function
that disappears right after it's called once.
And this might not appear
to make much sense right now.
But we actually need this technique later.
For example, with something called async/await.
So how could we do that?
Well, we could simply create a function.
And then only execute it once.
So, run, once, function.
This will never run again.
And then we can call it here.
However, we can actually run this function again.
At some other point in the code,
if we want it to, right?
There's nothing stopping us,
from later doing run once again, right?
And so this is not what we want to do.
We want to actually execute a function immediately.
And not even having to save it somewhere.
And so this is how we do that.
So we simply write the function expression itself.
So without assigning it to any variable.
Now, if we try to run this,
we will get an error for now.
So it says function statements require a function name.
And that's because
of course JavaScript here expects a function statement.
Because we simply started this line of code here
with the function keyword.
However, we can still trick JavaScript
into thinking that this is just an expression.
And we do that by simply wrapping all
of this into parentheses.
And so now,
we basically transformed the statement that we had before
into an expression.
And so now if we save this,
we get no error.
But also this function didn't execute yet, right?
We never called it.
So we know that this here is the function.
And so, we can then immediately call it.
And so with this,
we will get now this text here locked
to the console, to string.
And indeed here it is, alright?
So again this here,
is really just the function value.
So it's just a function expression.
And then immediately, we call it here.
And so this is why this pattern here,
is called the Immediately Invoked Function Expression.
Or IIFE for short.
So Immediately Invoked Function Expression.
And the same would of course,
also work for an arrow function.
So let's just copy this.
This will also never run again.
So if we try to call it like this,
then it would not work.
And so,
we actually don't get an error.
But also nothing happens.
So we first need to wrap this into parentheses.
And then as we called it.
Then here it is.
Okay, so two ways of writing
an Immediately Invoked Function Expression.
But you might be wondering,
why was this pattern actually invented?
Well, we already know that functions create scopes, right?
And what's important here
is that one scope does not have access
to variables from an inner scope, right?
For example, right here in this global scope.
We do not have access to any variables that
are defined in the scope
of any of these functions here, right?
So for example,
let's add a variable here.
Let's say, is private = 23.
And then as we tried to access it out here.
You already know that it's not going to work, right?
And that's because the scope chain
only works the other way around.
So the inner scope would have access
to anything defined outside,
here in the global scope.
But the other way around,
the global scope does not have access to anything,
that is inside of a scope.
So in this case,
of the scope created by this function here.
Therefore, we say that all data defined
inside a scope is private.
We also say that this data is encapsulated.
So for example, this is private here
is encapsulated inside of this function scope,
that's created here.
And data encapsulation and data privacy
are extremely important concepts in programming.
So many times we actually need to protect our variables,
from being accidentally overwritten by some other parts
of the program.
Or even with external scripts or libraries.
And I'm going to talk in detail about
these concepts in the object oriented programming section.
But for now, keep in mind that it's important
to hide variables.
And that scopes are a good tool for doing this.
And this is also the reason why
The Immediately Invoked Function Expressions were invented.
So basically, this pattern here.
So this is not really a feature, of the JavaScript language.
It's more of a pattern, that some developers came up with.
And that then started to being used,
by many other developers.
Now, do you remember what also creates a scope in ES6?
And that's right.
Variables declared with let or const create
their own scope inside a block.
And we learned that
in the behind the scenes section, remember?
So when we create a block, like this,
and declare is private in there.
Then the outside can still not access is private.
So let's comment out this one,
and paste it here.
And once again,
we cannot access this variable.
while on the other hand,
this one here,
would of course, be accessible.
And so again that's what we learned,
in one of the previous sections.
So that's because this one here was declared with var,
and therefore it does completely ignore
this block here essentially.
And this is the reason why now
in modern JavaScript.
Immediately Invoked Function Expressions are not
that used anymore.
Because if all we want
is to create a new scope for data privacy.
All we need to do,
is to just create a block like this, right?
There's no need to creating a function
to create a new scope.
Unless of course,
we want to use var for our variables.
But we already know,
we probably shouldn't do that. Right?
Now on the other hand,
if what you really need,
is to execute a function just once, then the IIFE.
So the Immediately Invoked Function Expression pattern
is still the way to go.
Even now with modern JavaScript.
And we will actually see a great use case a bit later
of doing an IIFE.
関連動画をさらに表示
Declaring Variables without Var, Let, Const - What Would Happen?
Javascript Interview Questions ( Var, Let and Const ) - Hoisting, Scoping, Shadowing and more
Hoisting in JavaScript 🔥(variables & functions) | Namaste JavaScript Ep. 3
Learn Closures In 7 Minutes
JavaScript if else (tutorial)
Closures | JavaScript 🔥 | Lecture 128
5.0 / 5 (0 votes)