typeof operator in JavaScript

typeof operator provides the data type of the argument ( value that is passed ). This operator is useful when you need to check the type of the variable. It returns the type as string.

typeof supports 2 syntax as a function and as an operator.

  • typeof()
  • typeof x

There is absolute no difference between typeof(operand) and typeof operand.


typeof true;  //output: "boolean"

typeof "str";  //output: "string"

typeof({});  //output: "object"

typeof(undefined);  //output: "undefined"

typeof Symbol();  //output: "symbol"

typeof(console.log);  //output: "function"

typeof(null);  //output: "object"
                    

In the above code, first 5 are clear. The last 2 needs additional explanation.
typeof(console.log) returns function. Because console.log is a function which we have already seen in previous section.
typeof(null) returns "object" which is strange because null is not an object. Some of the online documentation calls it an error of language. So rather You have to remember this thing.

Let us have a look at more examples.


//string

typeof "";
typeof "bcd"
typeof typeof 1;

//number

typeof 1.1;
typeof -13.3;
typeof NaN;
typeof Infinity;

//Boolean
typeof true;
typeof false;
typeof 1 !== 2;

//object
typeof new Object();
typeof new Date();
typeof {a:1};
typeof null;
typeof /1-9/; // /1-9/ is a regular expression

//function
typeof console.log;
typeof Math.abs;
typeof function(){};

//undefined
typeof abc; //abc is not declared
                    

Conclusion

In this section, you learned about typeof operator in JavaScript.
In next section, you will learn about Data type conversion in JavaScript.