Named Exports in JavaScript for Arithmetic Operations
Named Exports:
Write a JavaScript module that exports multiple named functions for basic arithmetic operations.
Solution-1:
JavaScript Code:
File: arithmetic.js
// --- file: arithmetic.js ---
// Export named functions for arithmetic operations
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export function multiply(a, b) {
return a * b;
}
export function divide(a, b) {
if (b === 0) {
throw new Error('Division by zero is not allowed');
}
return a / b;
}
File: app.js
// --- file: app.js ---
// Import specific functions
import { add, subtract, multiply, divide } from './arithmetic.js';
// Use the imported functions
console.log(add(10, 5));
console.log(subtract(10, 5));
console.log(multiply(10, 5));
console.log(divide(10, 5));
Output:
15 5 50 2
Explanation:
- arithmetic.js exports four named functions.
- app.js selectively imports the required functions using named imports.
- Each function performs a basic arithmetic operation, and the divide function includes error handling for division by zero.
Solution-2:
JavaScript Code:
File: mathOperations.js
// --- file: mathOperations.js ---
// Export functions inline during definition
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const multiply = (a, b) => a * b;
export const divide = (a, b) => (b !== 0 ? a / b : 'Cannot divide by zero');
File: main.js
// --- file: main.js ---
// Import all functions as an alias
import * as mathOps from './mathOperations.js';
// Use the imported functions
console.log(mathOps.add(7, 3));
console.log(mathOps.subtract(7, 3));
console.log(mathOps.multiply(7, 3));
console.log(mathOps.divide(7, 0));
Output:
10 4 21 Cannot divide by zero
Explanation:
- mathOperations.js defines and exports functions inline using arrow syntax.
- main.js imports all named exports as a single object using the alias 'mathOps'.
- This approach groups all related functions under one namespace, making the code modular and organized.
For more Practice: Solve these Related Problems:
- Write a JavaScript module that exports multiple named functions for basic arithmetic (add, subtract, multiply, divide) and test each operation in another file.
- Write a JavaScript module that exports named functions for converting temperatures between Celsius and Fahrenheit, and use them in a calculator page.
- Write a JavaScript module that exports two named functions: one to check if a number is prime and another to generate prime numbers up to a given limit.
- Write a JavaScript module that exports named functions to perform string manipulations (reverse, capitalize, and trim) and use them to format user input.
Go to:
PREV : Default Export.
NEXT : Import all as Alias.
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.