Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 11

Understanding Data Types with `typeof`

This lesson is built with resources from youtube.com, playcode.io and 1 more site.

Hello! Welcome to our next lesson.

In our last session, we explored the crucial difference between primitive types (like numbers and strings) and reference types (like objects and arrays), focusing on how they're stored in memory and how that affects copying and passing them to functions. This gave you a "deep dive" mental model of the Stack and the Heap.

Today, we'll build directly on that knowledge. Our goal is to learn how to use the typeof operator to determine the data type of a variable. Now that you know these different types exist, it's essential to have a tool to ask JavaScript, "What kind of data are you holding right now?" This is a fundamental skill for debugging and for writing code that can handle different kinds of data safely.

What is the typeof Operator?

At its core, typeof is a simple operator. You place it before a variable or a value, and it returns a string that tells you the data's type. Because JavaScript is a dynamically typed language (meaning a variable can hold a string one moment and a number the next), typeof is your way of checking the current state of things.

This short video provides a perfect introduction, showing the operator in action.

JavaScript Typeof Operator Explained

Watch this segment from the video 'JavaScript Typeof Operator Explained' by Future Fullstack. It clearly introduces the typeof operator and demonstrates its use on several primitive types.

Please watch from the beginning of the typeof explanation at 02:37 until 04:34. Pay attention to the string value that is returned for each different data type. Notice the surprising result for null—we will explore that right after.

As you saw, the basic usage is very straightforward:

let myAge = 30;
let myName = "Alex";
let isLearning = true;
let nothingHere; // This variable is declared but not assigned a value

console.log(typeof myAge);       // Output: "number"
console.log(typeof myName);      // Output: "string"
console.log(typeof isLearning);  // Output: "boolean"
console.log(typeof nothingHere); // Output: "undefined"

These results make perfect sense. But as the video hinted, there are a few very important "quirks" you need to know about to truly understand how JavaScript works.


The Quirks of typeof: Where Theory Meets History

Your preference for understanding the "why" behind concepts is especially important here. The behavior of typeof with null, arrays, and objects is directly linked to the memory model we discussed in the last lesson and even a bit of JavaScript history.

Let's dig into the details with a great article that explains these nuances.

JavaScript Data Types - Primitives vs. Objects

This article, 'JavaScript Data Types - Primitives vs. Objects' from codeguage.com, provides excellent explanations for the special cases of typeof.

Please read the following three short sections. They directly address the 'quirks' of the typeof operator: Start at the heading "How is null an 'object'?" to understand this famous historical bug. Continue to "How is an array an 'object'?" This section connects perfectly to our last lesson on reference types. Finally, read "How is a function not an 'object'?" to understand why functions get special treatment.

Let's summarize those crucial points:

  1. typeof null is "object": This is a famous, long-standing bug in JavaScript. It can't be fixed because doing so would break countless existing websites. The key takeaway is: you cannot use typeof to check for a null value. You must check for it directly with myVar === null.

  2. typeof on Arrays and Objects is "object": This is not a bug. As we learned, arrays and plain objects are both reference types. They are both fundamentally "objects" in the JavaScript engine. The typeof operator sees them as a reference to data in the Heap and correctly reports them as "object".

  3. typeof on Functions is "function": Even though functions are also a type of object (they are "first-class citizens," a concept we'll explore later), they are special because they are callable. The typeof operator gives them a unique type, "function", to reflect this special capability.

This summary table provides a fantastic visual reference for all the types we've discussed.

JavaScript typeof() Operator Return Type Summary
This table clearly shows the value returned by the `typeof` operator for each of JavaScript's main data types, including examples for `null`, `array`, and `object` which all have important nuances.
Test your understanding!

Based on what you've just learned, what will be logged to the console for each of the following lines?

1. console.log(typeof 42);
2. console.log(typeof "JavaScript");
3. console.log(typeof [1, 2, 3]);
4. console.log(typeof { topic: 'types' });
5. console.log(typeof null);
6. console.log(typeof function() {});
Show answer
  1. "number" - Straightforward, it's a number primitive.
  2. "string" - It's a string primitive.
  3. "object" - This is a key takeaway. Arrays are a type of object, so typeof reports "object".
  4. "object" - This is a plain object literal, so it's reported as "object".
  5. "object" - This is the historical bug. Even though null is a primitive type representing "no value", typeof reports it as an object.
  6. "function" - Functions are special objects that are callable, so typeof gives them their own distinct type string.

Putting It All Together: A Practical Guide to Type Checking

So, typeof is great for primitives (except null), but it can't distinguish between a plain object and an array. How do we deal with that in the real world?

Developers use typeof for quick checks and combine it with other tools for more specific situations. This guide provides a complete picture and introduces a best practice for checking for arrays.

JavaScript Data Types: Complete Guide with Examples

The 'JavaScript Data Types' guide from playcode.io offers a great summary table and introduces best practices for type checking.

Please review these sections to consolidate your knowledge and learn a best practice: Examine the "Data Types Reference" table. It's a great way to reinforce the typeof results. Read the section "Type Checking". Focus on the code examples and the explanation of the typeof null bug. Finally, look at the "Best Practices" section, specifically point #2: "Use Array.isArray() for Arrays". This shows you the correct way to identify an array, since typeof is not sufficient.

The most important best practice from that reading is: when you need to know if a variable is specifically an array, don't use typeof. Use the built-in Array.isArray() method, like this:

const myData1 = [1, 2, 3];
const myData2 = { a: 1, b: 2 };

console.log(typeof myData1);         // "object"
console.log(typeof myData2);         // "object"

// The correct way to check for an array:
console.log(Array.isArray(myData1)); // true
console.log(Array.isArray(myData2)); // false

Conclusion

Great work! You've now mastered the typeof operator, including its crucial quirks that trip up many beginners. Understanding not just what it does but why it behaves the way it does for null and reference types puts you on solid ground.

Key Takeaways:

  • The typeof operator returns a string indicating the type of a value or variable.
  • It works perfectly for string, number, boolean, undefined, symbol, and bigint primitives.
  • Quirk #1: typeof null returns "object". This is a historical bug. To check for null, use strict equality: myVar === null.
  • Quirk #2: typeof returns "object" for both arrays and plain objects because they are both reference types.
  • To reliably check if a variable is an array, use the Array.isArray() method.
  • Quirk #3: typeof returns "function" for functions, acknowledging their special status as callable objects.

In our next lesson, we will investigate what happens when you try to use a value as if it were a different type—for example, adding a number to a string. We will explore type conversion and coercion, another fundamental concept for writing robust JavaScript.