JavaScript typeof Operator Tutorial

In this section, we will learn what the typeof operator is and how to use it in JavaScript.

Note: we’re assuming you’re already familiar with JavaScript data types

What is typeof operator in JavaScript? (JavaScript Check Type )

Sometimes we need to know the current type of the value that is stored in a variable.

This is where we can use the `typeof` operator.

We put the name of the variable on the right side of this operator and it will return us the type of the value that is stored in that variable.

How to use typeof operator in JavaScript? (typeof operator syntax)

This is how we can use the typeof operator in JavaScript:

typeof variableName;

typeof value;

Example: using typeof operator in JavaScript

const num = 10;

const big = 234234234232354n;

const str = "This is a String value";

const obj = {};

const symbol = Symbol();

const bool = true;

console.log(typeof num);

console.log(typeof big);

console.log(typeof str);

console.log(typeof obj);

console.log(typeof symbol);

console.log(typeof bool);

Note that calling a variable will actually return a copy of its value and so here the `typeof` operator in fact is checking the value that is stored in each variable.

Basically, it’s the value that is checked and not the variable that is holding the value.

Example: applying typeof operator on String in JavaScript

console.log(typeof true);

console.log(typeof 33n);

console.log(typeof “test”);

We can also store the returned value of the `typeof` operator in a variable.

Example: typeof operator in JavaScript

let num = typeof 10;

let str = typeof num;

console.log(num);

console.log(str);

Output:

number

string

As you can see, in the first statement, the `typeof 10;` returned `number` as the type of the value `10`. But in the second statement `typeof num;`, the returned value is `string`.

Again, this is because the `typeof` operator returns a value of type `String` and so the current value that is stored in the `num` variable is “number” which is a String value.

Example: applying typeof operator on Object in JavaScript

const obj = {
  name: "John",
  lastName: "Doe"
}
console.log(typeof obj);

Output:

object
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies