How to Export Multiple Variables in JavaScript?

Estimated read time 1 min read

In JavaScript, you can export multiple variables from a module using the export keyword. To export multiple variables, you can define them within a single object and then export that object. Here’s an example code snippet that demonstrates this process:

// Define the variables to be exported
const myVar1 = 'Hello';
const myVar2 = 'World';

// Create an object to hold the variables
const myExportedVars = {
  var1: myVar1,
  var2: myVar2
};

// Export the object
export { myExportedVars };

In this example, we define two variables (myVar1 and myVar2) and then create an object called myExportedVars that holds these variables as its properties. We then use the export keyword to export the myExportedVars object.

To import the exported variables in another module, you can use the import statement like this:

// Import the exported variables
import { myExportedVars } from './my-module.js';

// Access the variables
console.log(myExportedVars.var1);
console.log(myExportedVars.var2);

In this example, we use the import statement to import the myExportedVars object from the my-module.js module. We can then access the variables within the object using dot notation (myExportedVars.var1 and myExportedVars.var2).

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply