Switch with function passing an object

PHOTO EMBED

Thu May 02 2024 06:15:07 GMT+0000 (Coordinated Universal Time)

Saved by @davidmchale #switch #statement #function #object

function calculate(options) {
  const num1 = options.num1;
  const operator = options.operator;
  const num2 = options.num2;

  let sum;

  // if the operator does not equal to plus minus multiply or subtract
  switch (operator) {
    case "+":
      sum = num1 + num2;
      break;

    case "-":
      sum += num1 - num2;
      break;

    case "*":
      sum += num1 * num2;
      break;

    case "/":
      sum += num1 / num2;
      break;

    default:
      sum = "Sorry no operator assigned";
      break;
  }

  return sum; // dont forget to return sum after the switch has executed
}

console.log(
  calculate({
    num1: 3,
    operator: "+",
    num2: 4,
  })
);
content_copyCOPY