What you'll learn
The basic kinds of values in JavaScript and how to check which kind you have.
Why it matters
JavaScript treats a number and a piece of text differently. Knowing the type of a value explains why "5" + 5 is not 10.
Explanation
The everyday types are:
- number:
42,3.14,-7. - string: text in quotes,
"hello"or'hello'. - boolean: only
trueorfalse. - undefined: a variable that has no value yet.
- null: "nothing" on purpose.
The typeof operator tells you the type of a value.
A string in quotes is always text, even if it looks like a number.
Example
const age = 30;
const city = "Pune";
const isStudent = false;
let nothingYet;
console.log(typeof age); // number
console.log(typeof city); // string
console.log(typeof isStudent); // boolean
console.log(typeof nothingYet); // undefined
console.log(5 + 5); // 10
console.log("5" + 5); // 55, text joined
console.log("5" * 2); // 10, text turned into a numberStep-by-step walkthrough
- Four variables are created, each with a different kind of value.
typeofprintsnumber,string,boolean, thenundefinedbecausenothingYetwas never given a value.5 + 5is number plus number, so the answer is10."5" + 5has a string on one side, so+joins them into the text55."5" * 2has no meaning for text, so JavaScript converts"5"to the number 5 first and gives10.
Try it yourself
Print the typeof of "42", 42 and true. Then try "10" - 3.
Check typesJavaScript
Common mistakes
- Adding a number and a numeric string.
"5" + 5is"55". Convert withNumber("5")first. - Writing
TrueorFalse. JavaScript is case-sensitive:trueandfalse. - Confusing
nullandundefined.undefinedmeans "never set",nullmeans "set to nothing". - Expecting
typeof nullto benull. It printsobject, a long-standing quirk.
Quick quiz
Summary
- Main types: number, string, boolean, undefined, null.
typeofreveals a value's type.+adds numbers but joins strings.
Next: making decisions with conditionals.