Mastering Immediately Invoked Functions and 'this'
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
(function () {
console.log('This is an IIFE example');
})();IIFEs help isolate scope, avoid global variable pollution, and create private environments for variables.
Example with Arguments
js
(function (num1, num2) {
return num1 + num2;
})(2, 2); // 4Preventing Loop Variable Issues
html
<div class="btn">1</div>
<div class="btn">2</div>
<div class="btn">3</div>
<div class="btn">4</div>
<script>
const btnEls = document.querySelectorAll('.btn');
for (let i = 0; i < btnEls.length; i++) {
const btn = btnEls[i];
(function (i) {
btn.onclick = function () {
console.log(`Button ${i + 1}`);
};
})(i);
}
</script>2. Object Types in JavaScript
Objects store key-value pairs and support dynamic data structures.
Object Creation Methods
Object Literal
js
const person = {
name: 'John',
age: 42,
speak() {
console.log('Hello');
},
};Constructor Function
js
function Person(name) {
this.name = name;
}
const p = new Person('Alice');Access and Modify
js
person.age = 40;
person['height'] = 180;
delete person.height;3. Memory Allocation
Stack Memory
Stores primitive values:
- number
- string
- boolean
- null
- undefined
- symbol
- bigint
Heap Memory
Stores reference types:
- objects
- arrays
- functions
Example:
js
const obj1 = { name: 'Tom' };
const obj2 = obj1;
obj2.name = 'Jerry';
console.log(obj1.name); // Jerry4. Value vs Reference Types
Value Types (Copied)
js
let a = 10;
let b = a;
b = 20;
console.log(a); // 10Reference Types (Referenced)
js
const data = { x: 5 };
const copy = data;
copy.x = 99;
console.log(data.x); // 995. Understanding this in JavaScript
this refers to the execution context. Its behavior changes depending on how a function is called.
5.1 Global Context
js
console.log(this); // window (in browsers)5.2 Object Method
js
const person = {
name: 'Alice',
greet() {
console.log(this.name);
},
};
person.greet(); // Alice5.3 Arrow Functions (Lexical this)
js
const obj = {
name: 'Rick',
show: () => console.log(this.name),
};
obj.show(); // undefinedArrow functions do not bind their own this.
5.4 Changing this with call/apply/bind
js
function greet() {
console.log(this.name);
}
const user = { name: 'Bob Marley' };
greet.call(user); // Bob MarleySummary
- IIFEs execute immediately and help avoid polluting the global scope.
- JavaScript objects can be created in multiple ways and are stored in heap memory.
- Primitive values use stack memory and are copied by value.
- Objects are reference types and share the same memory location.
-
thischanges depending on execution context; arrow functions capture lexicalthis.
Understanding these foundations helps you write clean, predictable, and efficient JavaScript.