Lesson · JavaScript Basics
Types, conversion, and strict equality
JavaScript can convert values implicitly, but explicit conversions make a program easier to understand.
What you will learn
- Identify strings, numbers, and booleans
- Convert text with Number
- Prefer strict equality
Common values
A string stores text, a number stores numeric data, and a boolean represents true or false. JavaScript also has null and undefined, which represent different kinds of absence. An array and many other structured values are objects, so checking types requires more than relying on a single operator.
Convert deliberately
Text read from a form is a string. Number can convert numeric text to a number, but invalid text produces NaN, a special numeric value meaning not-a-number. Check Number.isNaN when conversion can fail instead of allowing an invalid value to silently spread through later calculations.
Use strict equality
The strict equality operator compares without converting one side to match the other's type. For example, the string '5' is not strictly equal to the number 5. This is usually easier to reason about than loose equality, which can apply surprising coercion rules.
Inspect the value you have
When a comparison behaves unexpectedly, inspect both the value and its type. A visible string of digits may still be text. Convert at the point where data enters the program, and keep the original input when it is needed for an error message or display.
Handle absence and invalid numbers separately
undefined often means a property or return value was not provided; null is an explicit empty value. NaN is a numeric result that failed to represent a number. These cases require different checks. Before doing arithmetic on optional input, decide which absent values are allowed and what feedback a user should receive.
const text = '24';
const amount = Number(text);
console.log(typeof amount);
console.log(amount === 24);
Expected output
number
true
Practice exercise
Convert the text '12' to a number and check strictly whether the result is 12.
Show a hint
Use Number and ===.
Show one possible solution
const value = Number('12'); console.log(value === 12); prints true.
Quick check
Strict equality does not convert the string into a number.