JavaScript Under The Hood: The typeof Operator and Data Types Demystified
Tags: javascript
Published: 2023-08-02 18:38:34

As the sole front-end developer at a startup, I've found myself conducting technical interviews, primarily focused on JavaScript. My aim has been to gauge the fundamental understanding of the language among the candidates. I soon realized that many programmers lacked comprehension of the basics of JavaScript. Interestingly, some developers have even stopped using Google since the ChatGPT craze. This trend could be a potential setback for those engaged in developing large-scale software.

In this article, I will delve into the questionnaire I prepared and discuss the basic principles of JavaScript. I aim to cover the essentials in 3 parts, avoiding easily accessible details that are readily available on the internet. Let's start with the first part!

## Part 1: The 'typeof' Operator in JavaScript

In JavaScript, 'typeof' is an operator that returns a string indicating the type of the operand, which is the data type of the unevaluated operand.

Now, let's look at this code:

```js
console.log(typeof undefined)
console.log(typeof 10n)
console.log(typeof Symbol("id"))
console.log(typeof null)
console.log(typeof Math)
console.log(typeof alert)
console.log(typeof "a" / 2)
console.log(typeof NaN)
```

If you're familiar with the answers, that's excellent! If you can't answer all of them, let's delve into the reasons why.

---

## Understanding JavaScript Data Types

In JavaScript, a value is always of a certain type. There are eight data types in JavaScript:

- Undefined
- Null
- String
- Number
- Boolean
- Bigint
- Symbol
- Object

### Primitive Types

The primitive types include `string`, `number`, `bigint`, `boolean`, `symbol`, `null`, and `undefined`. All primitives are immutable; they cannot be altered. However, this does not apply to variables assigned with primitive values. Those variables can be reassigned to a new value, but the existing value cannot be changed. Primitives don't have methods, but JavaScript **auto-boxes** these values into wrapper objects when properties are accessed, allowing them to behave as if they do.

### Non-primitive (Reference) Types

The object type in JavaScript is unique. It can store collections of data and more complex entities like array, object, or date. Objects are the only mutable values. Functions are, in fact, also objects with the additional capability of being callable.

> 💡 In JavaScript, everything is essentially an object.

| Type | typeof return value | Object wrapper |
| --- | --- | --- |
| Null | "object" | N/A |
| Undefined | "undefined" | N/A |
| Boolean | "boolean" | Boolean |
| Number | "number" | Number |
| BigInt | "bigint" | BigInt |
| String | "string" | String |
| Symbol | "symbol" | Symbol |

## Understanding Specific 'typeof' Outputs
Let's dig deeper into the specific outputs of the 'typeof' operator we saw in our initial code snippet:

### typeof undefined
The special value undefined is unique and signifies an unassigned value.

### typeof null
The 'typeof' operator returning "object" for null is an officially recognized error in JavaScript, coming from its early days and kept for compatibility. In reality, null is a special value with a separate type of its own.

> 💡 Conceptually, undefined indicates the absence of a value, while null indicates the absence of an object.

### typeof 10n
The BigInt type was recently added to JavaScript to represent integers of arbitrary length. It's particularly useful for values larger than max safe integers.

### typeof Symbol("id")
Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object.

### typeof Math
Math is a built-in object that provides mathematical properties and methods.

### typeof alert
Interestingly, typeof alert returns "function" instead of "object". Functions in JavaScript belong to the object type, but 'typeof' treats them differently due to historical reasons.

### typeof "a" / 2
In this case, trying to divide a string by a number results in NaN, which stands for Not-A-Number. NaN represents a computational error resulting from an incorrect or undefined mathematical operation.

> 💡 Performing mathematical operations in JavaScript is remarkably flexible and failsafe. You can attempt any calculation: division by zero, interpreting non-numeric strings as numbers, and so forth. Rather than causing a fatal error that stops the script execution (or "dies"), JavaScript ensures the process continues. In the most extreme scenarios, you'll merely receive 'NaN' as the outcome, signifying an operation that doesn't result in a numerical value.

### typeof NaN
NaN is considered a number in JavaScript. This seeming contradiction is one of the interesting quirks of the language.

### P.S. About Arrays
Another note worth mentioning is the behavior of the 'typeof' operator when applied to arrays. In JavaScript, arrays are a special kind of object and this can lead to some unexpected results when using 'typeof'. For instance, if you try `console.log(typeof [])`, you might expect the result to be `array`. However, the output will be `object`. This is because, in JavaScript, arrays are essentially specialized objects. While this might seem confusing at first, it's one of the unique characteristics of JavaScript that you'll get accustomed to over time.

In summary: 

```js
console.log(typeof undefined) // "undefined"
console.log(typeof 10n) // "bigint"
console.log(typeof Symbol("id")) // "symbol"
console.log(typeof null) // "object"
console.log(typeof Math) // "object"
console.log(typeof alert) // "function"
console.log(typeof "a" / 2) // NaN => as "purple" in the console 😶‍🌫️
console.log(typeof NaN) // "number"
```

---

Grasping the fundamentals of any language, including JavaScript, is key. This language's versatility can both empower us and create room for confusion. To truly harness JavaScript's potential, we must understand its finer points, such as data types and operators like 'typeof'.

Bear in mind that no number of libraries or frameworks can supplant a robust understanding of the language's basics. Keep learning, explore new areas, and embrace each challenge as a learning opportunity. Utilize tools like MDN and JavaScript.info to further enrich your knowledge.

I welcome your feedback on this article, and I'm open to making edits where necessary. If you spot an error or have a suggestion, please get in touch. Together, we can create the most accurate and helpful content possible. Your input helps make this a learning journey for all of us. Thank you for reading, and I eagerly await your thoughts.

Stay curious, and happy coding!

Sources:

[Primitive - MDN Web Docs Glossary: Definitions of Web-related terms | MDN (mozilla.org)](https://developer.mozilla.org/en-US/docs/Glossary/Primitive)

[JavaScript data types and data structures | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures)

[Data Types - The Modern JavaScript Tutorial](https://javascript.info/types)