Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE8 querySelector null vs normal null

I just found really interesting behaviour in ie8. It turns out null is not always null.

// just normal, casual null hanging out in the sun
var nullA = null;
// query for non existing element, should get null, same behaviour also for getElementById
var nullB = document.querySelector('asdfasfdf');

// they are equal
console.log(nullA === nullB);

// false
nullA instanceof Object;

// will throw 'Object expected' error in ie8. Black magic
nullB instanceof Object;

Anyone has an explanation for that?

like image 855
Martin Velinsky Avatar asked Sep 10 '13 14:09

Martin Velinsky


1 Answers

So, Jan Dvorak is definitely right.

According to this answer, null is a native object and querySelector is a host object.

Host object behavior is not well defined in the ECMA specification, so its behavior is up to the implementation, and IE8 and IE10 have different JScript implementations, which is why, even in "IE8 Mode" the JavaScript engine in IE10 processes the objects differently (and better). It does appear that this particular host object in this particular implementation would be in violation of Sec 4.3.8 requiring it's prototype to be null or Object as it appears not to have inherited its instanceOf value.

It appears to be a bug in IE8 implementation of JScript (!== ECMAScript || JavaScript) that was fixed when they switched to the Chakra engine.

All that being said, if it hurts when you do that, don't do that. Just check to see if document.querySelector() === null.

Hope that sheds some light on it. For more info, see the linked answer, they did a great job explaining.

like image 78
Jason Nichols Avatar answered Oct 15 '22 05:10

Jason Nichols