Checking a Value's Kind with typeof
Introduction
Welcome to Comparing and Converting JavaScript Values! In the previous course, we stored values under names, changed some with let, and used arithmetic to work out new values. As programs grow, we also need to know what kind of value a name holds, because JavaScript treats numbers and text differently.
In this lesson, we will learn what a type is, meet the typeof operator, and use it to inspect numbers, text, and boolean values. By the end, we will be able to tell the difference between 3 and "3" even though they may look alike when printed.
A Value Has a Type
A value is one piece of information in a program, such as 7, "Alex", or true. A type describes what kind of information a value represents. We will work with three types here:
- A number represents a quantity, such as
7or4.5. - A string is text surrounded by quotation marks, such as
"Alex". - A boolean represents one of two choices:
trueorfalse.
The code tells us which type a value has. A number is written without quotation marks, while a string is written between quotation marks. The two can look similar in the editor, but JavaScript keeps their types distinct.
Asking JavaScript with typeof
We can ask JavaScript to report a value's type by placing the word typeof before the value. It produces a string containing the type name, which we can show with console.log:
When these lines run from top to bottom, each typeof result appears on its own line:
The output uses the words number, string, and boolean. These are the names JavaScript gives the types we have used. Notice that typeof itself does not change the value; it gives us information about the value.
Checking a Stored Value
We do not have to inspect only values written directly in the code. typeof also works with a variable name. JavaScript first looks up the value stored under that name, then reports its type:
Here pricePerCup holds a number, so JavaScript prints:
This can help us understand a program when the original value is far away from where it is used. We can inspect the name at the point where we need to know what it contains.
