Image of a cloud

Cloud Coding

Typeof Keyword in JS

By: Tristan Pedersen

Typeof Keyword in JS

typeof is a Javascript Keyword that will return a string to indicate the operand's value. The syntax would be:

typeof operand;

Here are a few examples:

typeof 5;
//output:'number'
typeof "hello";
//output:'string;
typeof [2, 3];
//output:'object'
typeof { age: 33 };
//output:'object'
typeof null;
//output:'object'

In the first implementation of JavaScript, Javascript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the null pointer (0x00 in most platforms). null had 0 as a type tag, this explains the typeof return value 'object'.

All constructor functions called with the new operator will return non-primitives; an object or function. Most will result in objects with the exception of function which will result in a function.

typeof is generally going to return a string for the value of the operand it is supplied with; even if the value is undefined. typeof will return 'undefined'. However using the typeof on lexical declarations (let, const, and class) in the same block before the value is initialized will result in a ReferenceError, since it will be in the temporal dead zone. See our article for more info. Var let and const is JS

Summary: The typeof operator in JavaScript gives back a string of the given operand's value. The operand can be any function, object or variable which gives you a great way to be able to see what data types you are working with.