Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>That is one of the "<a href="http://www.fishingforwater.net/archives/131" rel="nofollow noreferrer">Bad Parts</a>" of JavaScript, as a loosely typed language, the addition and concatenation operator is overloaded.</p> <p>JavaScript is loosely typed, but that doesn't mean that it has no data types just because a value of a variable, object properties, functions or parameters don't need to have a particular type of value assigned to it.</p> <p>Basically there are three <em>primitive</em> data types:</p> <ul> <li>boolean</li> <li>number</li> <li>string</li> </ul> <p>null and undefined are two special cases, everything else are just variations of the object type.</p> <p>JavaScript type-converts values of types into a type suitable for the context of their use (type coercion).</p> <p>In your example were trying to add two objects of type string, so a concatenation occur.</p> <p>You can "cast" or type convert the variables to <em>number</em> in many ways to avoid this problem:</p> <pre><code>var a = "2"; var b = "4"; // a and b are strings! var sum = Number(a) + Number(b); // Number constructor. sum = +a + +b; // Unary plus. sum = parseInt(a, 10) + parseInt(b, 10); // parseInt. sum = parseFloat(a) + parseFloat(b); // parseFloat. </code></pre> <p>This is I think a very common mistake, for example when reading user input from form elements, the value property of form controls is string, even if the character sequence that it contain represents a number (as in your example).</p> <p>The "Bad Part" which I talk, is about the dual functionality of the + operator, overloaded to be used for both, numeric addition and string concatenation. </p> <p>The operation that the + operator will do is determined completely by the context. Only if the both operands are numbers, the + operator perform addition, otherwise it will convert all of its operands to string and do concatenation.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload