Variables and Scope
In Node.js, you are writing JavaScript. But there are some important differences in how variables behave compared to browser JavaScript. Let me break it down.
Try it Yourself โvar, let, and const
You have three ways to declare variables:
// var - function scoped, can be redeclared
var name = "Alice";
var name = "Bob"; // This works
// let - block scoped, cannot be redeclared
let age = 25;
// let age = 30; // Error!
// const - block scoped, cannot be reassigned
const PI = 3.14159;
// PI = 3; // Error!
In Node.js, always use const by default. Only use let when you need to reassign a value. Never use var โ it causes confusing bugs with function scope.
Scope in Node.js
Scope determines where a variable is accessible. In Node.js, every file is its own module with its own scope:
// file1.js
const secret = "hidden";
console.log(secret); // Works here
// file2.js
console.log(secret); // Error! secret is not defined
Variables declared in one file are not automatically available in another. You must explicitly export and import them.
Module Scope
Every Node.js file is wrapped in a function. This means variables in a file are local to that file:
// This is what Node.js actually does:
(function(exports, require, module, __filename, __dirname) {
// Your code goes here
const localVar = "I am local";
});
This is why __dirname and __filename work โ they are injected into this wrapper function.
Best Practice: Use const for everything unless you need to reassign. Use let for loop counters and temporary variables. Never use var in modern Node.js code.