0
0
JavascriptConceptBeginner · 3 min read

What is typeof in JavaScript: Explanation and Examples

typeof in JavaScript is an operator that tells you the type of a value or variable, like if it is a number, string, or object. It returns a string describing the type, helping you understand what kind of data you are working with.
⚙️

How It Works

Think of typeof as a label maker for your data. When you give it a value, it tells you what kind of thing that value is, like labeling a box to know what's inside without opening it. For example, if you have a number, typeof will say "number"; if you have text, it will say "string".

This helps your program understand how to treat the value. Behind the scenes, typeof checks the value's type and returns a simple word that describes it. This is useful because JavaScript is flexible and lets you store different types of data in variables.

💻

Example

This example shows how typeof works with different values.

javascript
console.log(typeof 42);
console.log(typeof 'hello');
console.log(typeof true);
console.log(typeof { name: 'Alice' });
console.log(typeof undefined);
console.log(typeof null);
Output
number string boolean object undefined object
🎯

When to Use

Use typeof when you want to check what kind of data you have before doing something with it. For example, if you expect a number but get a string, you can catch that mistake early and avoid errors.

It is also helpful when writing functions that can accept different types of inputs and need to behave differently depending on the input type. For instance, you might want to treat text and numbers differently in your code.

Key Points

  • typeof returns a string describing the data type.
  • It works with all basic JavaScript types like number, string, boolean, object, undefined.
  • Note that typeof null returns "object", which is a known quirk.
  • It helps prevent errors by checking types before using values.

Key Takeaways

typeof tells you the type of a value as a string.
It is useful to check data types before processing values.
typeof null returns "object" due to JavaScript design.
Use typeof to write safer and more flexible code.