javaScript Classroom image

sumit  kandwal / Professional / Web Technology

 
To post your Question Join Classroom
 
Question No  (3 of 4)
First 1 I 2 I 3 I 4 Last
 
Question:-
Ques: What is a potential pitfall with using typeof bar === "object" to determine if bar is an object? How can this pitfall be avoided?
 
Answer:-

typeof bar === "object" is a reliable way of checking if bar is an object, the surprising gotcha in JavaScript is that null is also considered an object!

Therefore, the following code will, to the surprise of most developers, log true (not false) to the console:

var bar = null;
console.log(typeof bar === "object");  // logs true!
As long as one is aware of this, the problem can easily be avoided by also checking if bar is null:

console.log((bar !== null) && (typeof bar === "object"));  // logs false
To be entirely thorough in our answer, there are two other things worth noting:

First, the above solution will return false if bar is a function. In most cases, this is the desired behavior, but in situations where you want to also return true for functions, you could amend the above solution to be:

console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function")));
Second, the above solution will return true if bar is an array (e.g., if var bar = [];). In most cases, this is the desired behavior, since arrays are indeed objects, but in situations where you want to also false for arrays, you could amend the above solution to be:

console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]"));
Or, if you’re using jQuery:

console.log((bar !== null) && (typeof bar === "object") && (! $.isArray(bar)));

  
 
 
 
image
sumit  kandwal

Skills    javaScript

Qualifications :- High School - GIC, College/University - Graphic Era University,
Location :-Dehradun,Dehradun,UTTRAKHAND,
Description:- Having 10+ years of experience in Software development.
Explore
 

  Students (5)

Ask 
image
Pooja
Ask 
Neha
Ask 
image
Amit
Ask 
Pankaj
Ask 
Pankaj
 
 

Recommended Classes

image Anil Bist
I started my Professional Journey in 2006 with one of the Web Development Company in Bangalore an...
Professional
image shweta Pandey
Passionate about LIFE and Learning. Lets explore together better version of "self", &qu...
Professional
image shweta Pandey
Passionate about LIFE and Learning. Lets explore together better version of "self", &qu...
Professional