Immediately Invoked Function Expressions (IIFE) | JavaScript 🔥 | Lecture 127

The Coding Classroom
29 Apr 202307:53

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

00:00

🔍 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.

05:03

🔒 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)

An Immediately Invoked Function Expression (IIFE) is a JavaScript function that runs as soon as it is defined. The primary reason for using an IIFE is to obtain data privacy because it creates a new scope, preventing variables from being accessed by the global scope or other scripts. In the video script, IIFEs are presented as a pattern to execute a function only once and then discard it, which is useful in certain cases like async/await. The narrator demonstrates how to create an IIFE using a regular function expression and an arrow function, and explains why this pattern was invented.

💡Scope

Scope refers to the accessibility or visibility of variables within a specific part of a program. In JavaScript, variables have different scopes depending on how and where they are declared. The video script emphasizes the importance of scope in terms of data encapsulation and privacy, as variables defined within a scope (such as a function or a block) are not accessible from the outer scope. This concept is crucial for preventing accidental overwriting of variables and protecting data from external scripts or libraries. The narrator explains how scopes created by functions and blocks (with let and const) can be used to achieve data privacy.

💡Data Encapsulation

Data encapsulation is a principle in programming that involves bundling data and the methods that operate on that data into a single unit or object. The video script introduces this concept in the context of scopes, where variables defined within a scope are considered encapsulated or private, meaning they cannot be accessed from outside that scope. This is an important concept for protecting data and preventing unintended modifications. The narrator mentions that they will discuss data encapsulation in more detail in the object-oriented programming section.

💡Data Privacy

Data privacy refers to the protection of sensitive or confidential data from unauthorized access or misuse. In the context of the video script, data privacy is presented as one of the main reasons for using Immediately Invoked Function Expressions (IIFEs) and scopes created by blocks (with let and const). By encapsulating variables within a scope, developers can ensure that these variables are not accessible from the global scope or other parts of the program, thereby maintaining their privacy and preventing accidental modifications.

💡Block Scope

Block scope refers to the scope created by a pair of curly braces {} in JavaScript. Variables declared with let or const within a block have their scope limited to that block, meaning they are not accessible outside of it. The video script explains that in modern JavaScript, developers can use block scope instead of IIFEs to achieve data privacy, as block scope provides a more straightforward way of encapsulating variables without the need for creating a function.

💡Function Expression

A function expression is a way to define a function in JavaScript without using the function declaration syntax. Function expressions can be anonymous or named, and they can be assigned to variables or used immediately after being defined (as in the case of IIFEs). The video script demonstrates how to create an IIFE using a function expression wrapped in parentheses, which allows it to be treated as an expression and immediately invoked.

💡Arrow Function

Arrow functions, introduced in ES6 (ECMAScript 2015), provide a more concise syntax for defining functions in JavaScript. They are often used as function expressions and can be particularly useful in situations where a function needs to be passed as an argument or assigned to a variable. The video script shows how to create an IIFE using an arrow function, highlighting its compatibility with the IIFE pattern.

💡Global Scope

The global scope refers to the outermost scope in a JavaScript program, where variables and functions are accessible from anywhere in the code if they are not defined within a more specific scope (such as a function or a block). The video script emphasizes that variables defined within a function scope or a block scope are not accessible from the global scope, which is an important aspect of data encapsulation and privacy.

💡Scope Chain

The scope chain is the hierarchical order in which scopes are searched for variable and function declarations. In JavaScript, when a variable or function is referenced, the interpreter searches the current scope first, then moves up the scope chain to the outer scopes until it finds the declaration or reaches the global scope. The video script mentions that the scope chain works in one direction, allowing inner scopes to access variables from outer scopes but not vice versa.

💡Variable Declaration

Variable declaration is the process of introducing a new variable into a program, specifying its name and optionally assigning it an initial value. In JavaScript, variables can be declared using the var, let, or const keywords, each of which has different scoping rules. The video script highlights the importance of using let and const for modern variable declarations, as they respect block scope and contribute to better data encapsulation and privacy.

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

play00:01

Our next topic is something called,

play00:03

Immediately Invoked Function Expressions.

play00:07

So let's take a look at what they are.

play00:11

So sometimes in JavaScript,

play00:13

we need a function that is only executed once.

play00:16

And then never again.

play00:18

So basically a function

play00:20

that disappears right after it's called once.

play00:24

And this might not appear

play00:25

to make much sense right now.

play00:27

But we actually need this technique later.

play00:30

For example, with something called async/await.

play00:33

So how could we do that?

play00:36

Well, we could simply create a function.

play00:38

And then only execute it once.

play00:42

So, run, once, function.

play00:51

This will never run again.

play00:55

And then we can call it here.

play00:59

However, we can actually run this function again.

play01:03

At some other point in the code,

play01:05

if we want it to, right?

play01:07

There's nothing stopping us,

play01:08

from later doing run once again, right?

play01:14

And so this is not what we want to do.

play01:16

We want to actually execute a function immediately.

play01:20

And not even having to save it somewhere.

play01:22

And so this is how we do that.

play01:25

So we simply write the function expression itself.

play01:31

So without assigning it to any variable.

play01:35

Now, if we try to run this,

play01:36

we will get an error for now.

play01:40

So it says function statements require a function name.

play01:44

And that's because

play01:45

of course JavaScript here expects a function statement.

play01:49

Because we simply started this line of code here

play01:53

with the function keyword.

play01:54

However, we can still trick JavaScript

play01:57

into thinking that this is just an expression.

play02:01

And we do that by simply wrapping all

play02:03

of this into parentheses.

play02:06

And so now,

play02:07

we basically transformed the statement that we had before

play02:11

into an expression.

play02:13

And so now if we save this,

play02:15

we get no error.

play02:17

But also this function didn't execute yet, right?

play02:20

We never called it.

play02:23

So we know that this here is the function.

play02:25

And so, we can then immediately call it.

play02:28

And so with this,

play02:29

we will get now this text here locked

play02:32

to the console, to string.

play02:34

And indeed here it is, alright?

play02:38

So again this here,

play02:40

is really just the function value.

play02:43

So it's just a function expression.

play02:45

And then immediately, we call it here.

play02:47

And so this is why this pattern here,

play02:50

is called the Immediately Invoked Function Expression.

play02:55

Or IIFE for short.

play02:56

So Immediately Invoked Function Expression.

play03:00

And the same would of course,

play03:02

also work for an arrow function.

play03:07

So let's just copy this.

play03:11

This will also never run again.

play03:14

So if we try to call it like this,

play03:17

then it would not work.

play03:19

And so,

play03:21

we actually don't get an error.

play03:22

But also nothing happens.

play03:24

So we first need to wrap this into parentheses.

play03:27

And then as we called it.

play03:30

Then here it is.

play03:32

Okay, so two ways of writing

play03:34

an Immediately Invoked Function Expression.

play03:38

But you might be wondering,

play03:39

why was this pattern actually invented?

play03:43

Well, we already know that functions create scopes, right?

play03:48

And what's important here

play03:49

is that one scope does not have access

play03:52

to variables from an inner scope, right?

play03:56

For example, right here in this global scope.

play03:59

We do not have access to any variables that

play04:02

are defined in the scope

play04:04

of any of these functions here, right?

play04:07

So for example,

play04:10

let's add a variable here.

play04:14

Let's say, is private = 23.

play04:18

And then as we tried to access it out here.

play04:22

You already know that it's not going to work, right?

play04:26

And that's because the scope chain

play04:28

only works the other way around.

play04:31

So the inner scope would have access

play04:33

to anything defined outside,

play04:35

here in the global scope.

play04:37

But the other way around,

play04:38

the global scope does not have access to anything,

play04:40

that is inside of a scope.

play04:43

So in this case,

play04:44

of the scope created by this function here.

play04:47

Therefore, we say that all data defined

play04:50

inside a scope is private.

play04:53

We also say that this data is encapsulated.

play04:56

So for example, this is private here

play04:59

is encapsulated inside of this function scope,

play05:03

that's created here.

play05:04

And data encapsulation and data privacy

play05:08

are extremely important concepts in programming.

play05:12

So many times we actually need to protect our variables,

play05:16

from being accidentally overwritten by some other parts

play05:19

of the program.

play05:20

Or even with external scripts or libraries.

play05:24

And I'm going to talk in detail about

play05:25

these concepts in the object oriented programming section.

play05:29

But for now, keep in mind that it's important

play05:32

to hide variables.

play05:33

And that scopes are a good tool for doing this.

play05:36

And this is also the reason why

play05:38

The Immediately Invoked Function Expressions were invented.

play05:43

So basically, this pattern here.

play05:45

So this is not really a feature, of the JavaScript language.

play05:48

It's more of a pattern, that some developers came up with.

play05:52

And that then started to being used,

play05:54

by many other developers.

play05:57

Now, do you remember what also creates a scope in ES6?

play06:02

And that's right.

play06:03

Variables declared with let or const create

play06:06

their own scope inside a block.

play06:08

And we learned that

play06:09

in the behind the scenes section, remember?

play06:13

So when we create a block, like this,

play06:16

and declare is private in there.

play06:22

Then the outside can still not access is private.

play06:28

So let's comment out this one,

play06:30

and paste it here.

play06:32

And once again,

play06:33

we cannot access this variable.

play06:36

while on the other hand,

play06:39

this one here,

play06:40

would of course, be accessible.

play06:46

And so again that's what we learned,

play06:49

in one of the previous sections.

play06:52

So that's because this one here was declared with var,

play06:55

and therefore it does completely ignore

play06:58

this block here essentially.

play07:00

And this is the reason why now

play07:03

in modern JavaScript.

play07:05

Immediately Invoked Function Expressions are not

play07:08

that used anymore.

play07:09

Because if all we want

play07:10

is to create a new scope for data privacy.

play07:13

All we need to do,

play07:15

is to just create a block like this, right?

play07:18

There's no need to creating a function

play07:20

to create a new scope.

play07:22

Unless of course,

play07:23

we want to use var for our variables.

play07:26

But we already know,

play07:28

we probably shouldn't do that. Right?

play07:31

Now on the other hand,

play07:32

if what you really need,

play07:34

is to execute a function just once, then the IIFE.

play07:38

So the Immediately Invoked Function Expression pattern

play07:41

is still the way to go.

play07:43

Even now with modern JavaScript.

play07:45

And we will actually see a great use case a bit later

play07:48

of doing an IIFE.

Rate This

5.0 / 5 (0 votes)

您是否需要英文摘要?