Jump to content

Addition Problem

Recommended Posts

byyr contains 20. 

If I add 1, I get 201 (wrong result).  (See first set of code below)

If I multiply by 5, I get 100 (correct result).  (See second set of code below) 

If I multiply by 1, I get 100 (correct result). 

According to documentation, a + in Java Script is addition.

I have spent over 2 hrs trying to figure out what was wrong with my (more complicated) coding.

Please, please, tell me why addition doesn't work.


function mytab(byyr,bymo,mo,fld,to)
{with (byyr, bymo, mo, fld, to)
var x = byyr.value
var y = x + 1;

function mytab(byyr,bymo,mo,fld,to)
{with (byyr, bymo, mo, fld, to)
var x = byyr.value; 
var y = x * 5;


Link to post
Share on other sites

"+" is used for string concatenation. If the values are strings then they will use the string version of the "+" operator. You have to convert the value to a number before operating in order for it to work as you intend it to.

var x = Number(byyr.value);
var y = x + 1;


  • Like 1
Link to post
Share on other sites
  • 6 months later...

I like to use this hack when adding values in JS:

sum = -(-x - y);

It eliminates the ambiguous  '+' operator altogether, along with any type confusion.

It can also be put into a function:

function add(a, b) {return -(-a - b)}

sum = add(x, y);

This may be slightly less efficient than declaring the var as numeric, but I think it makes for neater code, and there are times we want to make use of JS's loose typing, so the var can be used as text in one place and numeric in another.

Edited by Jay@TastefulTitles.com
Link to post
Share on other sites

You can also preceed the string with a + to convert it to a number.

For example:

function mytab1(byyr,bymo) {
  var x = byyr,
      y = x + 1;     // expect 201
      z = +x +1;     // expect 21
  alert(y+' : '+z);
	  var a = bymo * 10; // expect 50
	mytab1('20','5');  // test

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...