JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to import functions from another file in JavaScript?

Depending upon how the functions are exported, you can import the functions in two ways:

1. When functions are exported as named exports. In that case, you use named import to access the exported functions.

import { function1, function2, ..., functionn } from './another-file.js';

Suppose you have a file utils.js that exports two functions, add() and multiply().

utils.js
export function add(a, b){
  return a + b;
}

export function multiply(a, b){
  return a * b;
}

To import the functions into the file, you need to run the following code:

app.js
import { add, multiply } from './utils.js';

console.log(add(10, 20)); //30
console.log(multiply(10, 20)); //200

2. When a function is exported as default export. In that case, you use default import to import the exported function. The syntax to import a default exported function is:

import functionName from './another-file.js';

Note: You don't use curly braces to import the default exported function.

The following code exports a functions using export default.

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

export function multiply(a, b){
  return a * b;
}

A file can only have one default exported value. To export more than one function, you export one of the functions as default and others as named exports.

Here is how you import the default exported functions in a file called app.js.

app.js
import add, {multiply} from './utils.js';

console.log(add(10, 20)); //30
console.log(multiply(10, 20)); //200

Recommended Posts