mickeymouse 0 Posted January 7, 2020 Report Share Posted January 7, 2020 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; alert(y);} function mytab(byyr,bymo,mo,fld,to) {with (byyr, bymo, mo, fld, to) var x = byyr.value; var y = x * 5; alert(y);} Quote Link to post Share on other sites
Ingolme 1,035 Posted January 7, 2020 Report Share Posted January 7, 2020 "+" 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; 1 Quote Link to post Share on other sites
Jay@TastefulTitles.com 0 Posted July 27, 2020 Report Share Posted July 27, 2020 (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)} 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 July 27, 2020 by Jay@TastefulTitles.com Quote Link to post Share on other sites
JMRKER 10 Posted July 28, 2020 Report Share Posted July 28, 2020 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 alert(y+' : '+z); var a = bymo * 10; // expect 50 alert(a); } mytab1('20','5'); // test </script> Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.