w3resource

Constants Export and Import in JavaScript Modules


Exporting Constants:

Write a JavaScript program to create a module that exports multiple constants. Use them in another file.

Solution-1: Using Named Exports

JavaScript Code:

File: constants.js

// constants.js
// Exporting multiple constants from constants.js
export const PI = 3.14159; // The mathematical constant Pi
export const EULER = 2.71828; // The mathematical constant Euler's number
export const GOLDEN_RATIO = 1.61803; // The golden ratio

File: main.js

//main.js
// Importing constants using named exports
import { PI, EULER, GOLDEN_RATIO } from './constants.js';

// Using the imported constants
console.log(`Value of PI: ${PI}`); // Logs 3.14159
console.log(`Value of Euler's Number: ${EULER}`); // Logs 2.71828
console.log(`Value of Golden Ratio: ${GOLDEN_RATIO}`); // Logs 1.61803

Output:

Value of PI: 3.14159
Value of Euler's Number: 2.71828
Value of Golden Ratio: 1.61803

Explanation:

  • constants.js exports three constants: PI, EULER, and GOLDEN_RATIO.
  • These constants are imported into main.js using named imports.
  • The constants are directly accessed and logged in the main file.

Solution-2: Using Default and Named Exports

JavaScript Code:

File: constants.js

// constants.js
// Exporting multiple constants, including a default export
const GRAVITY = 9.81; // The gravitational constant
export const LIGHT_SPEED = 299792458; // Speed of light in m/s
export const PLANCK = 6.626e-34; // Planck's constant

export default GRAVITY; // Default export

File: main.js

//main.js
// Importing the default constant and named exports
import GRAVITY, { LIGHT_SPEED, PLANCK } from './constants.js';

// Using the imported constants
console.log(`Value of Gravity: ${GRAVITY}`); // Logs 9.81
console.log(`Speed of Light: ${LIGHT_SPEED}`); // Logs 299792458
console.log(`Planck's Constant: ${PLANCK}`); // Logs 6.626e-34

Output:

Value of Gravity: 9.81
Speed of Light: 299792458
Planck's Constant: 6.626e-34

Explanation:

  • constants.js exports LIGHT_SPEED and PLANCK as named exports and GRAVITY as a default export.
  • In main.js, the default export is imported directly, while named exports are explicitly imported using curly braces.
  • All constants are accessed and logged in the main file.

Improve this sample solution and post your code through Disqus

Previous: Mastering Conditional Imports in JavaScript Modules.
Next: Mastering Aggregated Exports in JavaScript Modules.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.