JavaScript Type Conversion

Converting between strings, numbers and booleans.

✍️ 3 exercises + code challenge in this lesson

Values can be converted explicitly:

  • To number: Number("3.5"), parseInt(), parseFloat(), or unary plus +"3"
  • To string: String(42) or (42).toString()
  • To boolean: Boolean(value) or !!value

Automatic conversion

JavaScript also converts types automatically, sometimes surprisingly: "5" + 2 is "52" (string joining) but "5" - 2 is 3.

Key Takeaways: JavaScript Type Conversion

Mastering JavaScript Type Conversion helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Type Conversion Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
log(Number("3.5") + 1);
log(+"10" + 5);
log(String(42) + 8);
log(!!"hello", !!0);

log('"5" + 2 =', "5" + 2);
log('"5" - 2 =', "5" - 2);
log('"5" * "2" =', "5" * "2");
log("Number('abc') =", Number("abc"));
</script>
Free sign-in required · Google login available

JavaScript Type Conversion Practice Exercises

Check what you learned in “JavaScript Type Conversion”.

/ 3 solved
Fill in the blank

Convert the number to a string.

const text = (42);
✓ Correct! Not quite. Try again.
Multiple choice

What is "5" + 2?

✓ Correct! Not quite. Try again.
Code challenge

Convert "3.5" with parseFloat, multiply by 2 and log it.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services