Import And Export IN JavaScript

Import And Export IN JavaScript

Import & Export In JavaScript

  1. In JavaScript, there are two ways to import modules from other files: named imports and default imports.

  2. A named import allows you to import specific exports from a module by name. To use a named import, you need to wrap the exported names in braces {} when importing them. For example:

     // math.js
     export const add = (a, b) => a + b;
     export const subtract = (a, b) => a - b;
    
     // app.js
     import { add, subtract } from './math.js';
    
     console.log(add(2, 3)); // output: 5
     console.log(subtract(5, 2)); // output: 3
    
  3. In this example, we are importing the add and subtract functions from the math.js module using named imports.

  4. On the other hand, a default import allows you to import a single export from a module without specifying its name. To use a default import, you simply import the module without braces. For example:

     // math.js
     export default {
       add: (a, b) => a + b,
       subtract: (a, b) => a - b,
     };
    
     // app.js
     import math from './math.js';
    
     console.log(math.add(2, 3)); // output: 5
     console.log(math.subtract(5, 2)); // output: 3
    
  5. In this example, we are exporting an object with add and subtract properties as the default export from the math.js module. We can then import this default export in the app.js file by simply writing import math from './math.js'. Here, math is the name of the default export, and we can access its properties directly using dot notation (math.add, math.subtract, etc.).

  6. Note: that a module can have only one default export, but multiple named exports.