Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 1.5 — Type Conversion
JavaScript · Example 3 of 4

Implicit coercion with operators

In the last line, +"a" is NaN, which is then joined as text.

JavaScript converts values between types either when you ask (String(), Number(), Boolean(), parseInt, parseFloat) or automatically when an operator needs a different type; knowing the automatic rules prevents bugs like "5" + 1 giving "51".

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Convert the strings "19.5" and "0.5" to numbers and log their sum, which must be 20.

02

Read the width out of "240px" as a number, double it, and log 480px.

03

Predict, then check: "7" * "6", "7" + "6", "7" - - "6".

Explain it without notes

01

What is the difference between explicit conversion and coercion? Give an example of each.

02

When would you use Number() and when parseInt()/parseFloat()?

03

Explain the outputs of "5" + 1, "5" - 1 and 1 + 2 + "3".

04

Which values are falsy?

Implicit coercion with operators

Console

(nothing was printed)

Expected console output

51
4
12
33
123
2
1 NaN
[object Object]
baNaNa