Table of Contents
show
Example: 5A
Designing calculator using Arrow functions in JavaScript
Script
// Calculator using arrow functions
const prompt = require("prompt-sync")(); // required to get input from user
// Addition
const add = (num1, num2) => num1 + num2;
// Subtraction
const subtract = (num1, num2) => num1 - num2;
// Multiplication
const multiply = (num1, num2) => num1 * num2;
// Division
const divide = (num1, num2) => num1 / num2;
// Calculator function
const calculator = (operation, num1, num2) => {
switch (operation) {
case "+":
return add(num1, num2);
case "-":
return subtract(num1, num2);
case "*":
return multiply(num1, num2);
case "/":
return divide(num1, num2);
default:
return "Invalid operation";
}
};
const operation = prompt("Enter the input:(+, -, * , /)");
let number1 = prompt("Enter first number");
let number2 = prompt("Enter second number");
number1 = parseInt(number1);
number2 = parseInt(number2);
const result = calculator(operation, number1, number2);
console.log(`${number1} ${operation} ${number2} = ${result}`);
Output
Views: 33