0

I have this function:

function add(x,y)
{
  alert("sum is " + x+y);
}

When I call it with numbers, it doesn't add. So calling

add(1,2)

alerts

sum is 12

and not

sum is 3

like it should. Why? How can I alert the sum?

ilikechairs
  • 107
  • 1
  • 4

2 Answers2

1

By starting your expression as a string ("The sum is..."), JavaScript will evaluate the entirety of the expression as a string. Adding two strings together simply combines ("concatenates") them.

You can group (x + y) to cause it to be evaluated first/separately, similar to how order of operations might work in mathematics.

(For more information: Arithmetic operators in JavaScript)

function add(x, y) {
  alert("sum is " + (x + y));
}

add(5,2);

As I mentioned earlier, the expression is evaluated as a string because it starts with a string. But what if we started it with the addition instead?

function add(x, y) {
  alert(x + y + " is the sum");
}

add(5, 2);

Or possibly the best approach would be to simply use a template literal.

function add(x, y) {
  alert(`The sum is ${x+y}`);
}

add(5, 2);
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
0

The problem is a string comes before your numbers in the following line: alert("sum is " + x+y); - this will cause JavaScript to treat each item as a string that you want concatenated, as opposed to added. You can remedy that by simply doing the addition before the alert and storing in a variable. Something like this:

function add(x, y) {
  var sum = x + y;
  alert("sum is " + sum);
}

add(5, 10);
Tom O.
  • 5,730
  • 2
  • 21
  • 35
  • you can also do alert("sum is " + (x + y)), no need for a variable – Matthew Doyle Nov 05 '18 at 19:18
  • @MatthewDoyle Yes you could. Achieving this using a variable is not a worse approach as some people prefer to be more explicit - just a matter of preference. – Tom O. Nov 05 '18 at 19:20