Unable to add variable with number and number.

var num = 5; alert(num+5); 

The result is 55, but it should be 10. And if you add up like this ...

 alert(5+5); 

then everything is in order - it turns out 10.

What is the problem? What am I doing wrong? enter image description here

  • In your example, it is just that everything correctly counts - Cheg
  • And how then does the same thing show me not 10, but 55? This cannot depend on the jQuery library .... - Denis of Heaven
  • one
    Most likely you add a string with a number. The string is obtained because you take a value from the DOM node's string as the default. Give an error code. - Duck Learns to Take Cover
  • one
    Do you think to convince us in a picture that the code you give displays 55? - Cheg
  • one
    @DenisTimeless is another option to convert the string into int ru.stackoverflow.com/a/699604/191482 - Alexey Shimansky

1 answer 1

In the original code, your variable is a string and the operator, as expected, merges the string with the value 5. You need to call num = parseInt(num) to result in number and add two values.

  • one
    num = '0XF'; parseInt(num) === 15 num = '0XF'; parseInt(num) === 15 :) - andmalmal