Table of contents
Import & Export In JavaScript
In JavaScript, there are two ways to import modules from other files: named imports and default imports.
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
In this example, we are importing the
add
andsubtract
functions from themath.js
module using named imports.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
In this example, we are exporting an object with
add
andsubtract
properties as the default export from themath.js
module. We can then import this default export in theapp.js
file by simply writingimport 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.).Note: that a module can have only one default export, but multiple named exports.