r1 - 19 Sep 2005 - 11:23:59 - JonPriddeyYou are here: TWiki >  Main Web  >  ElixirReport > ElixirReportCookbook > AdditionAndConcatenation

Addition and Concatenation

JavaScript is a loosely typed language. This means you don't need to define the types of variables, JavaScript will infer them. For example, if you have two strings:

var a = '5';
var b = '6';
You can still perform a*b and get the value 30. This is because JavaScript knows that you can only multiply numbers, so it converts the strings to numbers automatically.

There is one problem. If you try a+b it returns 56, because the plus symbol applies to both strings and numbers. If one variable is a string and the other is a number, both will be converted to strings.

In order for JavaScript to assume the value is a number, we need to apply a numeric-only operation to it. The best one to use is the unary plus, basically putting a plus in front of the number. Here are some examples:

var a = +5; // a will always be treated as a number.
var total = a + b + c; // unsafe
var total = (+a) + (+b) + (+c); // safe - parenthesis added for readability
In many cases, there is no confusion. However, if you get results like NaN (Not a Number) the error may be due to accidental concatenation instead of addition.

-- JonPriddey - 19 Sep 2005

Edit | Attach | Printable | Raw View | Backlinks: Web, All Webs | History: r1 | More topic actions
 
Powered by TWiki
This site is powered by the TWiki collaboration platformCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback