JavaScript • Syntax and Core Types

Explicit Type Conversion — Convert types explicitly using Number(), String(), Boolean()

Take full control of your data types by deliberately converting values with JavaScript's built-in conversion functions.

JavaScript emblem with code brackets, braces, and a code file.
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

JavaScript was famously created in just ten days in 1995, and one of its most distinctive design choices was to make it a dynamically typed language. This means a variable can hold a number one moment and a string the next, without any special declaration. While this flexibility makes JavaScript beginner-friendly, it also introduces a subtle source of bugs: the language will sometimes convert types automatically behind the scenes, leading to surprising results. For example, "5" + 3 produces "53" (a string!) instead of 8. To fight this confusion, developers learned to convert values explicitly — making their intentions crystal clear in the code.

1995 • JavaScript Is Born

Brendan Eich creates JavaScript at Netscape. The language uses dynamic typing, meaning variables don't have fixed types. Implicit (automatic) conversions are baked into the language from day one.

1997 • ECMAScript 1 Standard

The first official ECMAScript specification formally defines the Number(), String(), and Boolean() conversion functions, giving developers reliable tools to convert types on purpose.

2009 • ES5 and Strict Mode

ECMAScript 5 introduces 'strict mode,' encouraging developers to write safer code. Best-practice guides begin recommending explicit type conversion over relying on implicit coercion.

2015–Present • Modern JavaScript & TypeScript

ES6+ and TypeScript reinforce the importance of type awareness. Explicit conversion remains a core skill, even as the language gains new features like template literals and optional chaining.

The central question this lesson addresses is straightforward: when you have a value of one type — say, the string "42" — and you need it as a different type — say, the number 42 — how do you make that conversion happen deliberately and predictably? The answer lies in three built-in functions: Number(), String(), and Boolean().

SECTION 2

Core Principles & Definitions

Before diving into examples, it helps to understand the key ideas that make explicit type conversion tick. JavaScript has three primitive types that you'll convert between most often: numbers, strings, and booleans. Each has a corresponding wrapper function that acts as a converter.

1

Explicit vs. Implicit

Explicit conversion means you, the programmer, write code that deliberately changes a value's type. Implicit conversion (also called coercion) happens automatically when JavaScript tries to "make things work" behind the scenes.
2

The Big Three Functions

Number(value) converts to a number. String(value) converts to a string. Boolean(value) converts to true or false. These are called without new — they return a primitive, not an object.
3

Predictable Rules

Each conversion function follows a fixed set of rules defined in the ECMAScript specification. There are no random outcomes — once you learn the rules, you can predict the result of any conversion.
4

Truthy & Falsy Values

When converting to boolean, JavaScript defines exactly six falsy values: false, 0, "", null, undefined, and NaN. Everything else is truthy.
✦

KEY TAKEAWAY

Think of explicit type conversion like translating between languages. If someone speaks Spanish and you need the message in English, you don't just hope someone nearby will translate it for you (implicit conversion) — you hire a translator and tell them exactly what to convert (explicit conversion). Number(), String(), and Boolean() are your translators — reliable, predictable, and always ready.

SECTION 3

Visual Explanation — The Conversion Pipeline

The diagram below shows how a single input value flows through each of the three conversion functions. Notice how the same input can produce very different outputs depending on which function you use. Understanding this pipeline is the key to mastering explicit type conversion.

Explicit Conversion Pipeline"42" (string)Number("42")String("42")Boolean("42")42 (number)"42" (string)true (boolean)Now try with an empty string """" (empty string)Number("") → 0String("") → ""Boolean("") → false
The top half shows the string "42" being passed through all three conversion functions. The bottom half reveals a tricky case: the empty string "" converts to 0, stays as an empty string, and becomes false.

As the diagram illustrates, the same value can become something completely different depending on which function you use. The string "42" converts nicely to the number 42 and to the boolean true (because it's a non-empty string). However, the empty string "" becomes 0 when converted to a number and false when converted to a boolean — two surprising results that catch many beginners off guard.

SECTION 4

How Each Conversion Works

Number() — Converting to Numbers

The Number() function tries to interpret its argument as a numeric value. If the value can be parsed as a number, you get that number. If it can't, you get NaN (Not a Number), which is JavaScript's way of saying "this doesn't make sense as a number." Here are the key rules: strings containing only digits (with optional leading/trailing whitespace) convert to the corresponding number; the empty string converts to 0; true becomes 1 and false becomes 0; null becomes 0; and undefined becomes NaN.

InputNumber() OutputWhy?
"123"123Digits only → parsed as integer
"3.14"3.14Valid decimal → parsed as float
""0Empty string is treated as zero
"hello"NaNNon-numeric string → not a number
true1Boolean true maps to 1
null0null is treated as "nothing" → 0
undefinedNaNundefined means "no value at all" → NaN

Number() conversion rules

String() — Converting to Strings

The String() function is the most straightforward of the three. It essentially wraps the value in quotes and produces a text representation. Numbers become their digit characters, booleans become the words "true" or "false", null becomes "null", and undefined becomes "undefined". There are virtually no surprises here.

Boolean() — Converting to Booleans

The Boolean() function returns either true or false. The rule is simple: memorize the six falsy values — false, 0, "" (empty string), null, undefined, and NaN. Every other value in JavaScript is truthy and converts to true. A common gotcha: the string "0" and the string "false" are both truthy because they are non-empty strings.

SECTION 5

The Falsy Values — A Complete Map

Understanding which values are falsy is arguably the most important skill for explicit conversion with Boolean(). The diagram below maps every falsy value and shows what it becomes when converted through all three functions. Memorizing these six values will prevent a huge number of bugs in your code.

THE 6 FALSY VALUES & THEIR CONVERSIONSFALSY VALUENumber()String()Boolean()false0"false"false00"0"false"" (empty)0""falsenull0"null"falseundefinedNaN"undefined"falseNaNNaN"NaN"false★ Everything NOT on this list converts to true with Boolean()
Complete reference table showing all six falsy values and what they produce when passed through Number(), String(), and Boolean(). Notice that the Boolean column is always false for these six values.
⚠

Watch Out!

The string "0" and the string "false" are NOT in the falsy list. They are non-empty strings, so Boolean("0") returns true. This is one of the most common mistakes beginners make!

SECTION 6

Worked Example — Cleaning User Input

Imagine you're building a simple web app that asks a user to enter their age into a text field. The value that comes back from an HTML input is always a string, even if the user typed a number. You need to convert it before doing any math. Let's walk through the conversion process step by step.

Converting User Input to a Usable Number

  1. 1

    Step 1 — Capture the Raw Input

    The user types "17" into the age field. In your JavaScript code, the variable userInput holds the value "17". Use typeof userInput to confirm it's a string.
    typeof userInput → "string"
  2. 2

    Step 2 — Convert to Number

    Apply Number() to the input: let age = Number(userInput);. Since "17" contains only digits, this converts cleanly to the number 17.
    age → 17 (type: number)
  3. 3

    Step 3 — Validate with Boolean()

    Before using the age, check if the conversion succeeded. If the user left the field blank, Number("") returns 0. We can use Boolean(age) — but wait, 0 is falsy! A better check is !Number.isNaN(age) && age > 0.
    Boolean(17) → true ✓ valid age
  4. 4

    Step 4 — Use the Converted Value

    Now you can do arithmetic: let canVote = age >= 18;. Since age is 17, the comparison returns false.
    canVote → false
  5. 5

    Step 5 — Display the Result with String()

    To show the user a message, convert the boolean back to text: String(canVote) returns "false". You might combine it into a sentence: "Eligible to vote: " + String(canVote).
    "Eligible to vote: false"

SECTION 7

Explicit vs. Implicit Conversion — A Comparison

You might be wondering: if JavaScript can convert types automatically, why bother with explicit conversion at all? The table below compares the two approaches side by side so you can see the tradeoffs.

FeatureExplicit ConversionImplicit Conversion (Coercion)
ReadabilityIntention is visible in the code — anyone can see that a conversion happensHidden — you must know JavaScript's coercion rules to understand what happens
PredictabilityYou choose the target type, so the result is always what you expectCan produce surprising results like "5" + 3 → "53"
DebuggingEasy to locate where conversions happen when tracking down bugsHard to find — conversions are invisible at the point they occur
Code LengthSlightly longer — you write Number(), String(), or Boolean()Shorter — relies on operators like + or == to trigger conversion
Best Practice?Yes — recommended by most style guides (Airbnb, Google, etc.)Generally discouraged, except in simple cases like Boolean checks in if-statements

Explicit vs. implicit type conversion

✦

KEY TAKEAWAY

Think of implicit coercion like auto-correct on your phone — sometimes it guesses right, but sometimes it changes your words into something embarrassing. Explicit conversion is like typing every word yourself: it takes a bit more effort, but you always get exactly what you intended. In professional JavaScript, explicit conversion is almost always the safer choice.

SECTION 8

Connections to Advanced Type Handling

Explicit type conversion with Number(), String(), and Boolean() is the foundation for more advanced type-handling techniques you'll encounter as you grow as a developer. The table below previews how these basics connect to what comes next.

This LessonWhat Comes Next
Number("42")parseInt("42px") and parseFloat("3.14rem") — parse numbers from strings that contain extra characters
String(42)num.toString(16) — convert a number to a hexadecimal string; num.toFixed(2) — format with decimal places
Boolean(value)Double-bang shorthand !!value — produces the same result as Boolean(value) but in fewer characters
Dynamic typing in JavaScriptTypeScript — a superset of JavaScript that adds static type annotations, catching type errors before your code even runs

From basics to advanced type handling

As you progress, you'll also encounter methods like JSON.parse() for converting JSON strings into full JavaScript objects, and JSON.stringify() for the reverse. These are essentially advanced forms of type conversion. The principles you've learned here — be deliberate, know the rules, and make your intent clear — will serve you in every one of these situations.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words why Boolean("0") returns true even though Boolean(0) returns false. What fundamental distinction does this illustrate?
Show answer
The value "0" is a string, not a number. Boolean() checks whether a value is falsy, and the only falsy string is the empty string "". Since "0" is a non-empty string (it contains the character '0'), it is truthy and converts to true. The number 0, on the other hand, is one of the six falsy values and converts to false. This illustrates that Boolean() cares about the type and the specific value, not about what the value 'looks like' to a human reader.

Question 2: BASIC CALCULATION

Predict the output of each expression: (a) Number(true) (b) String(null) (c) Boolean(" ") (a string with one space) (d) Number("")
Show answer
(a) 1 — true maps to 1 in JavaScript's Number conversion rules. (b) "null" — String() converts any value to its text representation, so null becomes the four-character string "null". (c) true — a string containing a space is NOT empty, so it's truthy. Only the completely empty string "" is falsy. (d) 0 — the empty string is a special case in Number() that converts to zero, not NaN.

Question 3: INTERMEDIATE

A user enters "25.5" into a form field. You want to calculate a 15% tip. Write a code snippet that: (1) converts the input to a number, (2) calculates the tip, and (3) converts the tip back to a string with a dollar sign. What is the final output string?
Show answer
The code would be: let bill = Number("25.5"); which gives 25.5. Then let tip = bill * 0.15; which gives 3.825. Finally, let result = "$" + String(tip); which produces "$3.825". Without the explicit Number() conversion in step 1, the expression "25.5" * 0.15 would still work due to implicit coercion, but using Number() makes the intent clear and avoids relying on hidden behavior.

Question 4: APPLIED

You're building a settings page where users can toggle a "dark mode" preference. The setting is stored in localStorage as a string (localStorage only stores strings). When you read the value back, you get "false". Explain why Boolean("false") does NOT give you the result you want, and propose a solution.
Show answer
Boolean("false") returns true because "false" is a non-empty string, and all non-empty strings are truthy. This is a classic trap. To properly convert a string representation of a boolean, you need to compare the string directly: let darkMode = (storedValue === "true");. This strict equality check returns true only when the stored string is literally "true", and false for anything else. Another approach is JSON.parse("false") which returns the actual boolean false. This scenario teaches us that Boolean() converts based on truthiness, not by parsing the word 'false'.

Question 5: CRITICAL THINKING

Consider the expression Number(null) === Number("") && Boolean(null) === Boolean(""). Predict whether this evaluates to true or false. Show your reasoning step by step. Then discuss what this tells us about the relationship between Number() and Boolean() conversions.
Show answer
Let's break it down. Number(null) → 0, and Number("") → 0. So 0 === 0 is true. Next, Boolean(null) → false, and Boolean("") → false. So false === false is true. Finally, true && true evaluates to true. This reveals that null and the empty string, while being fundamentally different values (one means 'no value' and the other means 'empty text'), produce identical results through both Number() and Boolean(). This shows that different types can converge to the same output, which is why you should always be aware of what type your original value is — two values that 'look the same' after conversion may not have been the same before.

SUMMARY

Summary — Explicit Type Conversion

Summary

Explicit type conversion is the practice of deliberately changing a value's type using JavaScript's built-in Number(), String(), and Boolean() functions. Unlike implicit coercion, which happens automatically and can produce unexpected results, explicit conversion makes your intentions visible and your code more predictable.

The key rules to remember: Number() converts valid numeric strings to numbers, empty strings to 0, and non-numeric strings to NaN. String() produces a text representation of any value. Boolean() returns false for exactly six falsy values (false, 0, "", null, undefined, NaN) and true for everything else. Mastering these rules is an essential step toward writing clean, bug-free JavaScript.

Varsity Tutors • JavaScript • Explicit Type Conversion — Convert types explicitly using Number(), String(), Boolean()