0

I make a simple calculator using javascript. I am providing those code below. But the problem is when i run those code. i saw a undefined output. I dont know why that text is showing. I want to remove that.

function addition(x, y) {
  var sum = x + y;
  document.write("Addition of two number is : " + sum);
}

function substract(x, y) {
  var sub = x - y;
  document.write("Subtraction of two number is : " + sub);
}

function multiply(x, y) {
  var multiply = x * y;
  document.write("Multipication of two number is : " + multiply);
}

function division(x, y) {
  var division = x / y;
  document.write("Division of two number is : " + division);
}

var x = parseInt(prompt("Enter the first number : "));
var y = parseInt(prompt("Enter the second number : "));

var operator = prompt("Enter the operator : ");

if (operator == "+") {
  document.write(addition(x, y));
} else if (operator == "-") {
  document.write(substract(x, y));
} else if (operator == "*") {
  document.write(multiply(x, y));
} else if (operator == "/") {
  document.write(division(x, y));
} else {
  document.write("Invalid Operator. Please choose operator between +,-,* or /. <br> Thanks for using our calculator. ");
}

Output

2
  • @Andy just because question has the same keywords "why" and "undefined" doesn't make it a common question. The proposed answered question is not helpful here. Commented Jul 10, 2021 at 11:55
  • @vanowm, but the question got solved ages ago. Functions return undefined if they don't return anything else. Commented Jul 10, 2021 at 12:33

2 Answers 2

0

Calling document.write(x) causes x to be written. If x is a function call, it will write whatever that function call returns. Since all of your functions don't explicitly return something, they return (here it comes) undefined.

Sign up to request clarification or add additional context in comments.

Comments

0

Your operator functions don't return anything, they write directly to the page. However the lines that execute these functions write to the page the return of these functions, which is undefined

So to solve this, you have 2 options:

  1. replace document.write("blah") with return "blah" in operator functions
  2. remove document.write() from the caller: document.write(addition(x, y))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.