Difference between require and import

1. Definition

require and import are used to include modules in JavaScript. require belongs to CommonJS, while import is part of ES Modules (ESM), the modern JavaScript standard.

2. require

  • Used in CommonJS
  • Synchronous loading
  • Can be used anywhere in the code
  • Default in older Node.js versions

3. import

  • Used in ES Modules (ESM)
  • Asynchronous loading
  • Must be used at the top level
  • Modern JavaScript standard

4. Key Differences

  • Syntax: require() vs import
  • Module System: CommonJS vs ES Modules
  • Loading: Sync vs Async
  • Usage: Flexible vs Top-level only

5. Example

👉 Using require

// math.js
module.exports = function add(a, b) {
  return a + b;
};

// app.js
const add = require("./math");
console.log(add(2, 3));

👉 Using import

// math.js
export default function add(a, b) {
  return a + b;
}

// app.js
import add from "./math.js";
console.log(add(2, 3));

6. When to Use

  • Use require in older Node.js projects
  • Use import in modern applications
  • Prefer import for frontend and full-stack apps

7. Advantages

  • require is simple and flexible
  • import provides cleaner and modern syntax
  • Better support with modern tools and frameworks