Strict mode & modules

In Node.js, how we organize code and how strictly that code is executed are two sides of the same coin. Here is a breakdown of Strict Mode and the Module Systems.

Strict Mode


Strict Mode is a way to opt into a restricted variant of JavaScript. It makes it easier to write "secure" JavaScript by turning silent errors into real ones that stop the execution.


How to Enable It

In traditional scripts, you enable it by adding "use strict"; at the very top of your file.


What It Changes

  • Eliminates Silent Errors: In normal JS, if you accidentally assign a value to a non-existent variable, it becomes a global variable. In Strict Mode, this throws a ReferenceError.


  • Prevents Deletions: You cannot delete variables, functions, or arguments.


  • Unique Parameters: It requires function parameters to have unique names (e.g., you can't have function sum(a, a) {}).

  • Secure this: In normal mode, if a function isn't a method, this defaults to the global object. In strict mode, this remains undefined, preventing accidental changes to the global scope.


Without Strict Mode:

function setAge() {
  age = 25; // No 'var', 'let', or 'const' used
}
setAge();
console.log(age); // 25 (pollutes the global scope)

With Strict Mode:

"use strict";
function setAge() {
  age = 25; // Throws ReferenceError: age is not defined
}
setAge();


In the browser, this often defaults to window. In Node.js, it defaults to the global object. Strict mode keeps it undefined to prevent accidental modifications to the environment.

"use strict";
function checkThis() {
  console.log(this); 
}

checkThis(); // Output: undefined


Module Systems

Modules are the building blocks of a Node.js application. They allow you to split your code into multiple files, making it maintainable and reusable. Node.js currently supports two systems: CommonJS and ES Modules.


1. CommonJS (CJS)


This is the original, default module system in Node.js.

  • Syntax: Uses require() to import and module.exports to export.


  • Execution: Modules are loaded synchronously. The code waits for the file to be read before moving to the next line.

  • Strict Mode: CommonJS does not enable strict mode by default; you must manually add "use strict"; at the top of each file.


This is the default system in Node.js. It uses require and module.exports.

math.js (The Module)

const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

// Exporting multiple items as an object
module.exports = {
  add,
  subtract
};


app.js (The Main File)

// Importing the module
const math = require('./math');

console.log(math.add(5, 3));      // Output: 8
console.log(math.subtract(10, 4)); // Output: 6


2. ES Modules (ESM)


This is the modern standard used in browsers and increasingly in Node.js (supported via the .mjs extension or by setting "type": "module" in package.json).


  • Syntax: Uses import and export.

  • Execution: Modules are loaded asynchronously, which is more efficient for modern web architectures.

  • Strict Mode: ES Modules are always in strict mode by default. You don't need to add "use strict"; at the top.


Key Differences in Behavior

The environment changes depending on which system you use:


Filename Variables In CommonJS, you have access to __dirname and __filename. These do not exist in ES Modules. Instead, you have to use import.meta.url to find your file path.


Top-Level Await ES Modules allow you to use the await keyword at the top level of your script without wrapping it in an async function. CommonJS requires an async wrapper.


Importing Logic require() can be called conditionally inside an if statement or a function. import statements must generally stay at the top of the file (unless using dynamic import()), which allows tools like Vite or Webpack to perform "Tree Shaking" (removing unused code to keep the bundle small).


Dynamic vs. Static


CommonJS allows you to load modules conditionally inside a function or an if block, whereas ES Module imports must stay at the top level.


utils.js


// Named Export
export const multiply = (a, b) => a * b;

// Default Export
const greet = (name) => `Hello, ${name}`;
export default greet;