Use-Cases of this Tutorial
- Find the type of a variable - null, string, array etc.
Javascript provides 2 operators to check the type of a given value :
typeof : This checks whether the value is one of the primitive data types. It will return a string specifying the type — "undefined" / "string" / "number" / "boolean" / "object" etc.
instanceof : This checks the "kind" of an object. For example, Javascript arrays are basically objects. Using this we can check whether a given value represents an array.
instanceof will return a boolean true / false depending on whether the value is an instance of a given object or not.
Checking for undefined
typeof operator will return "undefined" for an undefined value.
var a;
// "Undefined value"
if(typeof a == "undefined")
console.log("Undefined value");
else
console.log("Defined value");
Alternatively you can use the strict equality operator to check for undefined.
var a;
// "Undefined value"
if(a === undefined)
console.log("Undefined value");
else
console.log("Defined value");
Checking for null
Unfortunately due to a Javascript bug, typeof operator on null will return the type as "object".
So we need to use the strict equality operator === to check for a null.
var b = null;
// "Null value"
if(b === null)
console.log("Null value");
else
console.log("Not null value");
Checking for a Number
typeof operator will return "number" for a numeric value.
var a = 5;
// "Numeric value"
if(typeof a == "number")
console.log("Numeric value");
else
console.log("Not a number");
Checking for a String
typeof operator will return "string" for a string of characters.
var a = 'Tree';
// "String value"
if(typeof a == "string")
console.log("String value");
else
console.log("Not a string");
Checking for a Boolean
typeof operator will return "boolean" for boolean values (true / false).
var a = true;
// "Boolean value"
if(typeof a == "boolean")
console.log("Boolean value");
else
console.log("Not a boolean");
Checking for an Object
typeof operator will return "object" if the value represents an object.
var a = { key: "value" };
// "Object"
if(typeof a == "object")
console.log("Object");
else
console.log("Not an object");
Checking for an Array
typeof operator on an array will return "object" (as Javascript array is an object internally). However sometimes we need to check whether the value represents an array or not.
Ths can be done with the instanceof operator. This will check whether the value is a specific "kind" of an object.
var a = [1, 2, 3];
// "Represents an array"
if(a instanceof Array)
console.log("Represents an array");
else
console.log("Does not represent an array");