JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to export variables using JavaScript?

JavaScript Module system allows you to export a single variable or multiple variables using named export. There are two ways of using named export:

1. Export individual variables by writing export at the beginning of their declaration.

app.js
export let msg = 'Hello, World!';
export let arr = [10, 20, 30, 40];

2. Export variables after they have been declared by exporting them as an object.

app.js
let msg = 'Hello, World!';
let arr = [10, 20, 30, 40];

export {msg, arr};

After exporting them, you can import the variables using the import keyword.

template.js
import {msg, arr} from './app.js'

console.log(msg); //'Hello, World!'

console.log(arr); //[10, 20, 30, 40]

There is another way of exporting variables which is default export. Using default export, you can export only a single variable. If you try to use multiple export defaults in a file, you will get an error.

app.js
export default let msg = 'Hello, World!';

//The below line will give error.
export default let arr = [10, 20, 30, 40];

Let's import the variable exported as default.

template.js
import msg from './app.js';

console.log(msg); //'Hello, World!'

You can also use named and default exports in a single file.

app.js
let msg = 'Hello, World!';
export let arr = [10, 20, 30, 40];

export default msg;

Here, is how you would use import default and named imports simultaneously.

template.js
import msg, {arr} from './app.js';

console.log(msg); //'Hello, World!'

console.log(arr); //[10, 20, 30, 40]

Recommended Posts