Course outline · 0% complete

0/29 lessons0%

Course overview →

Dynamic types and typeof

lesson 2-2 · ~8 min · 5/29

Types live on values, not variables

Why care about types at all? Because most beginner JavaScript bugs are type bugs: a number that is secretly the string "5", a variable that is undefined because nothing was ever assigned. Knowing the six types below, and how to check them, turns hours of confusion into seconds of diagnosis.

Like Python, JavaScript is dynamically typed: a variable can hold a number now and a string later. The type belongs to the value currently inside.

The types you will use constantly:

TypeExample valuesPython cousin
number42, 3.5int and float
string"hi"str
booleantrue, falseTrue, False
undefinedundefined(no direct match)
nullnullNone
object{...}, [...]dict, list

Two things jump out. Booleans are lowercase: true, not True. And there are two "nothing" values: undefined means "no value was ever put here" (a declared variable you never assigned), while null means "a person deliberately stored nothing here", like Python's None.

Asking a value its type

Python has type(x). JavaScript has the typeof operator, which gives back the type name as a string:

typeof 42        // "number"
typeof "42"      // "string"
typeof true      // "boolean"
typeof undefined // "undefined"

One famous oddity you will eventually meet: typeof null answers "object". That is a bug from 1995 that can never be fixed without breaking the web. To test for null, compare directly: x === null.

Code exercise · javascript

Watch the type follow the value. x starts as a number, then the SAME variable holds a string. Run it and read each typeof result.

Code exercise · javascript

Your turn. Declare three const variables: pi holding 3.14, language holding the string JavaScript, and learning holding true. Then print typeof for each, one per line.

Code exercise · javascript

Second practice. Declare nickname with let and NO value, then print its typeof. Declare middleName as a const holding null (deliberately nothing), then print whether it is strictly equal to null.

Quiz

What does console.log(typeof "3.14") print?