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?
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?
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);
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);