Beginner 5 min
Types, conversions, and equality
JavaScript values have types such as number, string, and boolean.
How it works
If input comes from a text field, it starts as a string even if it contains digits. Decide whether to keep a value as text or convert it into a number before comparing or adding. For example, adding a numeric string can join text while adding two numbers calculates a sum.
Walk through an example
Use typeof to inspect most value types. 5 === "5" is false because one side is a number and the other is text. Number("5") turns numeric text into a number.
What to watch for
Check user input deliberately. Number("") gives 0, which may hide a missing value if you meant to reject an empty field.
Code example
console.log(5 === "5");
console.log(Number("5") === 5);Check your understanding
Is this comparison true or false?
See the example and explanation
- Worked example
- Given
Number('8') === 8 - Answer
true
The conversion produces the number 8, so the two operands have the same type and value.