Variable coercion/conversion

Download javascript eBook


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).

Related Examples


213 Contributors: 20
Tuesday, January 10, 2017
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook