In this episode, we'll explore how modules actually work behind the scenes. We'll dive into how modules load into a page and how Node.js handles multiple modules, focusing on a deep dive into the module.exports
and require
functions
In JavaScript, when you create a function…
function x () {
const a = 10;
function b () {
console.log("b");
}
}
Will you be able to access this value? no
console.log(a);
//op - a is not defined
A:
You cannot access a
value outside the function x
because it is defined within the function's scope. Each function creates its own scope, so variables inside a function are not accessible from outside that function.
To learn more about scope, check out this video: Understanding Scope in JavaScript.
module.exports
. This allows you to export specific elements from the module, making them accessible when required elsewhere in your application.require
. This function is not a regular function; it’s a special type known as an IIFE (Immediately Invoked Function Expression). Here’s how it works:(function () {
// All the code of the module runs inside here
})();
In this pattern, you create a function and then immediately invoke it. This is different from a normal function in JavaScript, which is defined and then called separately:
function x() {}
x();
Using IIFE solves multiple problems by providing scope isolation and immediate execution.
Q1: How are variables and functions private in different modules?