-2

I am a beginner at programming, i always stumble upon this problem whenever i am trying to add numbers, instead of adding, it concatenates. Please someone explain what is happening here and some solutions so that i would not come across these type of problems again thanks ^^

function add(x,n) {
let result = x + n;
return result;
}

let x = prompt();
let n = prompt();

alert ( add(x,n) );

if i have x=5 and n=2 it should alert 7, but it shows 52. however if i use different arithmetic operators, it works. if i use -, it subtracts.

1 Answers1

-1

The problem is that prompt is returning a string. x is "5" and n is "2" (not 5 and 2).

One option is to use parseInt to convert these values to integers.

function add(x, n) {
  let result = parseInt(x) + parseInt(n);
  return result;
}

let x = prompt();
let n = prompt();

alert(add(x, n));
skovy
  • 5,430
  • 2
  • 20
  • 34