JavaScript Variable coercion/conversion

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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



Got any JavaScript Question?