Programming with JavaScript

⌘K
  1. Home
  2. Docs
  3. Programming with JavaScri...
  4. Practice Programs
  5. Calculator using Arrow functions

Calculator using Arrow functions

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

Loading

Views: 33

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments