Convert Values Explicitly

Convert Values Explicitly

Form fields supply strings. Number converts a numeric string to a number before arithmetic, while the plus operator can concatenate when a string participates. Validate converted values before treating them as marks.

Before this topic, review Values and Data Types if its terms are unfamiliar.

What you’ll learn

  • Explain convert values explicitly through the school example.
  • Trace the shown operations and distinguish their result from displayed output.
  • Make the practice change and explain its consequence: The first operation joins text; the explicit conversion makes the second operation addition.

Work through the school example

This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.

JavaScript · school.js · complete example

const input = "72";
console.log(input + 2);
console.log(Number(input) + 2);

Expected output

722
74
Run in JavaScript compiler →

Introduction to Type Conversion in JavaScript

JavaScript is a loosely typed language. This means you can assign different types of values to the same variable without any error. But how does JavaScript handle the change of types under the hood? That's where Type Conversion comes in.

There are two types of type conversions in JavaScript:

  • Implicit Conversion – performed automatically by JavaScript
  • Explicit Conversion – manually triggered by developers

Implicit Type Conversion (Type Coercion)

JavaScript often converts types behind the scenes to make the code work, which can sometimes lead to unexpected results. This is called type coercion.

Example 1: Number + String

let result = 5 + "5";
console.log(result);
console.log(typeof result);
55
string

Explanation: When a number is added to a string, JavaScript converts the number to a string and performs string concatenation instead of arithmetic addition.

Example 2: Boolean in Arithmetic

let value = true + 2;
console.log(value);
3

Explanation: The boolean true is implicitly converted to 1, so the result becomes 1 + 2 = 3.

Example 3: null and undefined

console.log(null + 1);      
console.log(undefined + 1);
1
NaN

Explanation: null is treated as 0 in numeric contexts, but undefined becomes NaN (Not a Number).

Explicit Type Conversion

This is when you intentionally convert data from one type to another using built-in functions like String(), Number(), and Boolean().

Converting to String

let num = 100;
let str = String(num);
console.log(str);
console.log(typeof str);
100
string

Converting to Number

let str = "42";
let num = Number(str);
console.log(num);
console.log(typeof num);
42
number

Converting to Boolean

console.log(Boolean(0));
console.log(Boolean("hello"));
console.log(Boolean(""));
false
true
false

Explanation: Falsy values like 0, "", null, undefined, and NaN convert to false. All other values are considered true.

Using Unary Plus (+) for Type Conversion

let str = "99";
let num = +str;
console.log(num);
console.log(typeof num);
99
number

Explanation: The unary + operator is a quick way to convert strings to numbers.

Complex Coercion Examples

Adding Objects and Primitives

console.log({} + []);
console.log([] + {});
[object Object]
[object Object]

Explanation: When used with +, both objects and arrays are converted to strings if one operand is not numeric.

Comparisons with Type Coercion

console.log(0 == "0");
console.log(false == "false");
true
false

Explanation: The double equals == performs type coercion. In the first case, both values are coerced to number, hence 0 == 0. In the second, false is coerced to 0, but "false" remains a string.

Best Practices

  • Prefer === and !== over == to avoid implicit coercion bugs.
  • Always use explicit conversions where clarity matters.
  • Understand falsy and truthy values in control flow conditions.

Truthy vs Falsy Values in Practice

let input = "";
if (input) {
  console.log("User provided input");
} else {
  console.log("No input given");
}
No input given

Explanation: An empty string is falsy, so the else block executes.

Conclusion

Type conversion is a foundational part of JavaScript’s flexibility, but it can also lead to confusion if not understood properly. By mastering both implicit and explicit conversions, you'll write more predictable and robust code.

Always be mindful of what type your variables are, and don’t hesitate to be explicit when needed. It’s not just cleaner — it’s safer.

Recognize the important boundary

Number('') is 0, and invalid numeric text can become NaN. Check empty text, finiteness and the allowed range separately.

Try a small variation

JavaScript · original source for practice

const input = "72";
console.log(input + 2);
console.log(Number(input) + 2);

Your task: Replace '72' with '80'. Predict the result before running the edited program.

The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.

Worked answer and reasoning

The first operation joins text; the explicit conversion makes the second operation addition.

JavaScript · complete worked variation

const input = "80";
console.log(input + 2);
console.log(Number(input) + 2);

Expected output

802
82
Run in JavaScript compiler →

Predict the original program

JavaScript · original program for this question

const input = "72";
console.log(input + 2);
console.log(Number(input) + 2);
What does the original JavaScript program display, in order?
Choose one answer. You can try again.

Answer and explanation

722 → 74

Form fields supply strings. Number converts a numeric string to a number before arithmetic, while the plus operator can concatenate when a string participates. Validate converted values before treating them as marks. Number('') is 0, and invalid numeric text can become NaN. Check empty text, finiteness and the allowed range separately.

Check the important distinction

Which input check avoids accepting an empty mark as zero?
Choose one answer. You can try again.

Answer and explanation

Reject trimmed empty text, then check the converted number and allowed range.

This separates presence, numeric validity and the school rule.

Keep the useful idea

Form fields supply strings. Number converts a numeric string to a number before arithmetic, while the plus operator can concatenate when a string participates. Validate converted values before treating them as marks.

Check your variation against this explanation: The first operation joins text; the explicit conversion makes the second operation addition.

Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Operators and Comparisons →