JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to import variables from another file in JavaScript?

If a variable is named exported, then you import it like this:

import {variable1, variable2} from './file.js';

On the other hand, if a variable is default exported, then you import it in this way:

import variable1 from './file.js';

Note: In default import, you don't use curly braces.

Let's understand how to import variables with the help of an example.

Here, we have exported two variables as named export and one variable as the default export.

export let msg = 'How are you?';
export let greeting = 'Good Morning';

let str = "What a pleasant weather!";
export default str;

This is how you import the variables in app.js file.

import str, { msg, greeting } from './utils.js';

msg = 'Hello Mohit';




How are you?
Hello Mohit
Good Morning
What a pleasant weather!

As you can see from this example, you are free to make changes to the imported variable.

Recommended Posts