Data types and the typeof operator
Strings, numbers, booleans, null and undefined — plus why typeof null is a lie.
Lesson 2 of 23 in JavaScript9 min1 exercise
JavaScript has seven primitive types: string, number, boolean, null, undefined, symbol and bigint. Everything else — objects, arrays, functions, dates — is an object at heart.
- string — text:
'hello',"hello", `hello` - number — one type for integers and decimals:
42,-1.5,NaN,Infinity - boolean —
trueorfalse - null — an intentional empty value you set yourself
- undefined — the value of something that was never set
typeof 42; // "number"
typeof "42"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" <- famous bug, keep it in mind
typeof []; // "object" <- arrays are objects
Array.isArray([]); // trueCoercion: when types get mixed
JavaScript converts values when an operator expects a different type. "5" * 2 is 10, but "5" + 2 is "52" because + also means concatenate. This is why strict equality === matters — it compares without converting.
Number("12"); // 12
Number("12px"); // NaN
String(12); // "12"
Boolean(""); // false
Boolean("hi"); // true
Number.isNaN(Number("12px")); // trueTry it
Ask JavaScript what type things are
main.js
console · output appears here
Exercises
Checked in your browser · hints and solutions included
01
Exercise
Describe any value
Write describeValue(value) that returns:
"null"when the value isnull"array"when it is an array- otherwise the result of
typeof value
So describeValue([]) is "array", describeValue(null) is "null", and describeValue(7) is "number".
exercise.js
console · run your code or check the answer