JavaScript typeof Operator Example

In this short post, we will learn the basics of the JavaScript typeof Operator.
In JavaScript, any value has a type assigned. The typeof operator is a unary operator that returns a string representing the type of a variable.

Syntax

The typeof operator is followed by its operand:
typeof operand

Basic Examples

// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof(42) === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number('1') === 'number'; // Number tries to parse things into numbers


// Strings
typeof '' === 'string';
typeof 'bla' === 'string';
typeof `template literal` === 'string';
typeof '1' === 'string'; // note that a number within a string is still typeof string
typeof (typeof 1) === 'string'; // typeof always returns a string
typeof String(1) === 'string'; // String converts anything into a string, safer than toString


// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(1) === 'boolean'; // Boolean() will convert values based on if they're truthy or falsy
typeof !!(1) === 'boolean'; // two calls of the ! (logical NOT) operator are equivalent to Boolean()


// Symbols
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'


// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined'; 


// Objects
typeof {a: 1} === 'object';

// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === 'object';

typeof new Date() === 'object';
typeof /regex/ === 'object'; // See Regular expressions section for historical results


// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === 'object'; 
typeof new Number(1) === 'object'; 
typeof new String('abc') === 'object';


// Functions
typeof function() {} === 'function';
typeof class C {} === 'function';
typeof Math.sin === 'function';

typeof Operator with Object Properties

typeof works also on object properties. Let's create a user object with the following properties in it:
// using Object Literals
var user = {
    emailId : 'ramesh@gmail.com',
    age : 29,
    getFullName : function (){
        return user.firstName + " " + user.lastName;
    }
};
Note that firstName and lastName properties not added to the above user object.
This is how you check if the firstName and lastName properties are defined on this user object:
function isUndefined(user) {
    if(typeof user.firstName === 'undefined'){
        console.log("User first name is undefined");
    }

    if(typeof user.lastName === 'undefined'){
        console.log("User last name is undefined");
    }
}
Let's call the above function:
isUndefined(user);
Output:
User first name is undefined
User last name is undefined

Comments