JavaScript Development Space

How to Use Immediately Invoked Functions and this in JavaScript

This guide covers the basics of JavaScript's immediately invoked function expressions (IIFE), object handling, memory allocation, and the use of this in object-oriented programming. It explores key concepts, from IIFE syntax to object creation and data handling techniques.

1. Introduction to Immediately Invoked Function Expressions (IIFE)

An Immediately Invoked Function Expression (IIFE) is a JavaScript function that runs as soon as it is defined.

js
1 (function() {
2 console.log("This is an IIFE example");
3 })();

Implementing an IIFE

  • Define an anonymous function.
  • Wrap the function in parentheses and immediately follow it with () to execute it.

Example:

js
1 (function(num1, num2) {
2 return num1 + num2;
3 })(2, 2); // 4

Why Use an IIFE?

  • Scope Isolation: IIFE creates a local scope, reducing conflicts with global variables. This is crucial in large projects or collaborative development.
  • Avoids Polluting the Global Scope: Variables and functions inside an IIFE are not accessible outside of it.

Example: Prevent variable conflicts with for loops:

html
1 <div class="btn">1</div>
2 <div class="btn">2</div>
3 <div class="btn">3</div>
4 <div class="btn">4</div>
5
6 <script>
7 const btnEls = document.querySelectorAll(".btn");
8 for (let i = 0; i < btnEls.length; i++) {
9 const btn = btnEls[i];
10 (function(i) {
11 btn.onclick = function() {
12 console.log(`Button ${i + 1}`);
13 }
14 })(i);
15 }
16 </script>

2. Using Object Types in JavaScript

In JavaScript, objects are a powerful data structure allowing storage of complex data through key-value pairs.

Creating Objects

There are several ways to create objects:

1. Object Literal:

js
1 const person = {
2 name: "John Doe",
3 age: 42,
4 speak() {
5 console.log("Hello");
6 }
7 };

2. Using new Object():

js
1 const person = new Object();
2 person.name = "John";

3. Object Constructor Function:

js
1 function Person(name) {
2 this.name = name;
3 }
4 const person = new Person("John");

Accessing and Modifying Properties

Properties can be accessed via dot notation or bracket notation.

js
1 person.name; // Access
2 person["age"] = 42; // Modify

Adding and Deleting Properties

Properties can be added or deleted dynamically.

js
1 person.height = 186;
2 delete person.height;

3. Memory Allocation in JavaScript

JavaScript has two primary types of memory: stack memory and heap memory.

  • Primitive data types (numbers, strings, booleans) are stored in stack memory.
  • Reference data types (objects, arrays, functions) are stored in heap memory.

This distinction is important for understanding how data is passed and manipulated in JavaScript.

4. Understanding Value and Reference Types

  • Value Types: Primitive data types are copied by value. Modifying one variable does not affect others.
  • Reference Types: Object types are copied by reference, meaning modifying one affects all references to that object.

Example:

js
1 const obj = { name: "Maya" };
2 const ref = obj;
3 ref.name = "John";
4 console.log(obj.name); // Outputs: "John"

5. Working with this in JavaScript Functions

The this keyword refers to the object that called the function. Its value depends on the context in which a function is called.

Basic Usage of this

  1. Global Scope: In the global scope, this refers to the global window object.
  2. Object Methods: Inside an object method, this refers to the object itself.
  3. Arrow Functions: this in arrow functions takes the value from the enclosing lexical context, making it ideal for callback functions where this should not change.

Example:

js
1 const person = {
2 name: "Alice",
3 greet() {
4 console.log(this.name);
5 }
6 };
7 person.greet(); // Outputs: "Alice"

Changing the Context of this

The context of this can be changed using call, apply, or bind.

Example:

js
1 function greet() {
2 console.log(this.name);
3 }
4
5 const person = { name: "Bob Marley" };
6 greet.call(person); // Outputs: "Bob Marley"

Summary

This guide has provided an overview of IIFE, object manipulation, memory handling, and the this keyword in JavaScript. These concepts are foundational for both front-end and back-end JavaScript development, providing the tools to write efficient, conflict-free code and manage complex data interactions effectively.

JavaScript Development Space

© 2024 JavaScript Development Space - Master JS and NodeJS. All rights reserved.