Understanding Function Context and IIFE in JavaScript
Learn about function context and Immediately Invoked Function Expressions (IIFE).
1. Function Context
In JavaScript, the context of a function refers to the value of this
within that function. The value of this
is determined by how a function is called, not where it is defined.
const channel = {
name: "DeathCode",
subscribers: "2.04k",
print: function() {
console.log(this);
}
};
// channel.print(); // Logs the channel object
// channel.name = "Gaming";
// channel.print(); // Logs the updated channel object
In the above code, when channel.print()
is called, this
refers to the channel
object. If we change the name property and call print
again, it reflects the updated object.
Arrow Functions and Context
Arrow functions do not have their own this
context; they inherit this
from the surrounding lexical context. This means that if you use an arrow function inside an object method, this
will not refer to the object.
const fun2 = () => {
console.log(this);
};
In this case, this
will refer to the global object (or undefined
in strict mode) instead of the channel
object.
Returning Values in Arrow Functions
In arrow functions, if you want to return a value directly, you can omit the curly braces:
const fun4 = () => ({ name: "DeathCode", val: "44" });
However, if you need to perform multiple operations or return something conditionally, you must use curly braces:
const fun5 = () => {
return { name: "DeathCode", val: "44" };
};
In this case, the curly braces indicate the start and end of the function body, and you must explicitly use the return
statement.
2. Immediately Invoked Function Expression (IIFE)
An IIFE is a function that runs as soon as it is defined. It is a common JavaScript pattern used to create a new scope and avoid polluting the global scope.
(() => {
console.log("Started");
})();
This code defines an arrow function and immediately invokes it, logging "Started" to the console.
(function() {
console.log("Started 2");
})();
This is a traditional function expression that is also immediately invoked. It will log "Started 2" to the console.