Getting started · Lesson 4 of 45
Type conversion
Number, String, Boolean, and the values that count as false.
8 minutes3 games
Sometimes a number arrives as text (like a value typed into a form) and you need to calculate with it. JavaScript converts types in two ways:
- Explicit (you ask for it):
Number("42"),String(42),Boolean(1). - Implicit (JavaScript does it for you): like
"5" * 2giving10.
JavaScript
const input = "42"
console.log(input + 8) // "428": joined
console.log(Number(input) + 8) // 50
console.log(Number("12px")) // NaN
console.log(parseInt("12px")) // 12
console.log(String(99) + "!") // "99!"Truthy and falsy
In any condition JavaScript turns the value into a boolean. Only 6 values count as false (they're falsy); everything else is truthy:
falsy =
false[0]
0[1]
""[2]
null[3]
undefined[4]
NaN[5]
Even "0", "false", [] and {} are truthy.
JavaScript
console.log(Boolean("")) // false
console.log(Boolean("0")) // true
console.log(Boolean([])) // true
const name = ""
if (!name) {
console.log("Please enter your name")
}What's the output?
console.log("10" * 2)
console.log("10" + 2)What will this code print?
Quick question
Which value is truthy?
Exercise
Both values arrive as text. Print their sum as a number (30).
Expected output: 30
JavaScript
const a = "12" const b = "18"
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.