How to Create a Basic Calculator in JavaScript (SMonkey 60.2.3) Using Sample Code?

Estimated read time 2 min read

Here’s an example of how you can create a basic calculator in JavaScript using the sample code:

function calculate(num1, num2, operator) {
  switch (operator) {
    case "+":
      return num1 + num2;
      break;
    case "-":
      return num1 - num2;
      break;
    case "*":
      return num1 * num2;
      break;
    case "/":
      return num1 / num2;
      break;
    default:
      return "Invalid operator";
  }
}

In this example, the function calculate takes three parameters: num1, num2, and operator. The switch statement is used to determine the operation to perform based on the value of operator. If operator is "+", the function returns the sum of num1 and num2. If operator is "-", the function returns the difference of num1 and num2, and so on. If the value of operator doesn’t match any of the cases, the function returns an error message "Invalid operator".

You can call the calculate function and pass in the values for the parameters:

let result = calculate(10, 5, "+");
console.log(result); // Output: 15

In this example, result will store the value returned by the calculate function when it is called with num1 equal to 10, num2 equal to 5, and operator equal to "+". The value of result will then be logged to the console, which will display 15.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply