JavaScript edit

Variable coercion / conversion


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:

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

Table Of Contents
16 Variable coercion / conversion
17 Map
18 Set
28 Date
104 Tilde
107 Events
  ↑ ↓ to navigate     ↵ to select     Esc to close