Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Data Types  ›  Lesson

Strings, Numbers and Booleans

string 12 minStrings hold text, numbers hold whole and decimal values as floating-point numbers, and booleans hold true or false.

Strings, Numbers and Booleans

In short: every value is text, a number or a yes/no, and JavaScript tells them apart by how the value is written, not by what it looks like. Quotes at the two edges make a string, even if the quoted text is all digits. Bare digits with no quotes make a number. The bare words true/false make a boolean. Get this wrong and "214" behaves nothing like 214.

Three incoming values sorted by their edges: a quoted "214" goes to the string bin, a bare 214 goes to the number bin, a bare true goes to the boolean bin, with a trap box showing "false" in quotes is a string, not a boolean

A song length typed into a form

Every value a listener types into a web form arrives as a string, even a length like 214 seconds. Add 6 seconds of fade-out the careless way and you get a mess:

javascript

"214" + 6 joins text because one side is a string: "2146". Converting first with Number() gives the number you actually wanted, 220. The bug is never in the maths — it's in trusting that a typed value is already a number.

Averaging two star ratings

Numbers cover both whole numbers and decimals with one type, and that type is a 64-bit floating-point value under the hood. Most of the time that's invisible; sometimes it bites:

javascript

4.5 + 4.2 is 8.7, fine — but 0.1 + 0.2 is 0.30000000000000004, not 0.3. Some decimals simply cannot be stored exactly in binary. Never compare two decimals with ===; compare the difference instead, or round first with .toFixed(2).

A "logged in" flag that never logs anyone out

A boolean is exactly true or false, nothing else, and it drives every if. The trap is a look-alike string:

javascript

loggedInText holds the five-letter string "false", and every non-empty string is truthy, so the if runs. Only the real boolean false skips it. Storing flags as text and forgetting to convert them back is one of the most common bugs in JavaScript.

Classifying four valuesStep 1 of 4
  1. 214

    No quotes, digits inside: a number.

Quick practice

quick drill

What type is the value "42"?

quick drill

What does console.log("Song: " + "Blue Hour".length) print?

quick drill

What does 0.1 + 0.2 === 0.3 evaluate to?

quick drill

A settings object stores darkMode: "false" (a string). What happens in if (darkMode) { enableDark(); }?

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainText that looks like a number

A form asks for a song's length and the listener types 214. The code does input.value + 6 and shows 2146 instead of 220. Explain why, in terms of types, and what type the code needed.