Variable coercion / conversion

suggest change

Remarks

Some languages require you to define ahead of time what kind of variable you’re declaring. JavaScript doesn’t do that; it will try to figure that out on its own. Sometimes this can create unexpected behavior.

If we use the following HTML

<span id="freezing-point">0</span>

And retrieve its content through JS, it will not convert it to a number, even though one might expect it to. If we use the following snippet, one might expect boilingPoint to be 100. However, JavaScript will convert moreHeat to a string and concatenate the two string; the result will be 0100.

var el = document.getElementById('freezing-point');
var freezingPoint = el.textContent || el.innerText;
var moreHeat = 100;
var boilingPoint = freezingPoint + moreHeat;

We can fix this by explicitly converting freezingPoint to a number.

var el = document.getElementById('freezing-point');
var freezingPoint = Number(el.textContent || el.innerText);
var boilingPoint = freezingPoint + moreHeat;

In the first line, we convert "0" (the string) to 0 (the number) before storing it. After doing the addition, you get the expected result (100).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Variable coercion / conversion:

Table Of Contents
11 Arrays
12 Objects
14 Classes
15 Variable coercion / conversion
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde