Search⌘ K
AI Features

Exercise: Calculator

Understand how to use if-else statements to perform mathematical operations based on operator values. Learn to add, subtract, multiply, and divide numbers conditionally, and handle invalid operators by assigning NaN.

We'll cover the following...

Task

A data analyst wants to do mathematical operations on a series of values. He was able to extract multiple operands and label them as left and right operands. He extracted operators too. The only task left is the operation itself. He converted types of operands to number, but left the operator to the string type. Your task: to write code which does the mathematical operation depending on the value of the operator.

Problem statement

You are given three variables named left_operand, right_operand, and operator. Write code for operator values so that each value does the following:

  • '+': Add left_operand to right_operand and assign the result to ans.
  • '-': Subtract left_operand from right_operand and assign the result to ans.
  • '*': Multiply left_operand with right_operand and assign the result to ans.
  • '/': Divide left_operand with right_operand and assign the result to ans.
  • For any other operator, assign NaN to ans.

Remember, there are a lot of ifs to what the operator is. Find a solution to all ifs.

Good luck!

Javascript (babel-node)
left_operand = left_operand; // Left operand is assigned here
right_operand = right_operand; // Right operand is assigned here
operator = operator; // This is the String representation of operator
ans = ans; // Assign final answer to ans
// Following is an Array of all possible operators
let all_operators= ['+','-','*','/'];