How to Export Constants in JavaScript?

Estimated read time 2 min read

In JavaScript, you can export constants from a module by using the export keyword. Here’s an example of how to export a constant:

// constants.js
export const PI = 3.14159;
export const MAX_VALUE = 100;

In this example, we define two constants (PI and MAX_VALUE) and use the export keyword to make them available to other modules.

To use these constants in another module, you can import them like this:

// app.js
import { PI, MAX_VALUE } from './constants.js';

console.log(PI); // 3.14159
console.log(MAX_VALUE); // 100

In this example, we import the PI and MAX_VALUE constants from the constants.js module using destructuring syntax. We can then use them just like any other variable in our app.js module.

Alternatively, you can export the constants as a single object using the export default syntax. Here’s an example:

// constants.js
const PI = 3.14159;
const MAX_VALUE = 100;

export default { PI, MAX_VALUE };

In this example, we define the constants as properties of an object and export that object as the default export of the module. We can then import them like this:

// app.js
import constants from './constants.js';

console.log(constants.PI); // 3.14159
console.log(constants.MAX_VALUE); // 100

In this case, we import the default export of the constants.js module as an object named constants. We can then access the constants as properties of that object.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply