agyanadda@gmail.com

JS Type Conversion

Strings and Numbers 1 min read Updated Dec 1, 2026 Topic 12 of 38

Values often need converting — for example, form inputs are always strings.

To number

  • Number('42') → 42
  • parseInt('42px') → 42 (reads digits from the start)
  • parseFloat('3.5kg') → 3.5
  • Number('abc') → NaN

To string

  • String(42) → '42'
  • (42).toString() → '42'

To boolean

Boolean(value) — but you rarely need it, because JavaScript checks truthiness in if.

Falsy values

These count as false: false, 0, '', null, undefined, NaN. Everything else is truthy, including '0' and [].

Example

Example — Adding two inputs correctly HTML
<input id="x" value="10" size="4"> +
<input id="y" value="5" size="4">
<button onclick="add()">Add</button>
<pre id="out"></pre>

<script>
  function add() {
    const x = document.getElementById('x').value;
    const y = document.getElementById('y').value;
    document.getElementById('out').textContent =
      'Without converting: ' + (x + y) + '\n' +
      'With Number(): ' + (Number(x) + Number(y));
  }
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does parseInt('25px') return?

Exercise 2 True / False

An empty string '' is falsy.

Exercise 3 Fill in the Blank

Values from input fields are always of type ___.

Frequently Asked Questions

The unary plus converts a value to a number: +'5' is 5. Number('5') does the same and is easier to read.