## 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.

```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;

##### 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;```

##### Share on other sites
• 6 months later...
Posted (edited)

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)}

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
##### Share on other sites

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

For example:

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

## Join the conversation

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

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.