Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js, why does `isFunction` use `|| false`?

The optional override for isFunction(object) in Underscore.js (repo link to definition), reads as follows:

// Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
// IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
var nodelist = root.document && root.document.childNodes;
if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
    _.isFunction = function(obj) {
        return typeof obj == 'function' || false;
    };
}

What I'm confused about is the || false, why is it necessary after a string comparison? Since typeof always returns a string there should be no ambiguity?
The comment states the override fixes some typeof bugs, are there cases on the listed platforms when typeof doesn't return a string?

like image 439
Etheryte Avatar asked Aug 08 '16 10:08

Etheryte


1 Answers

See the issues covered in the comments, #1621, #1929 and #2236.

Shortly put, some platforms have a bug where typeof isn't a string unless you store it in a variable.
The || false fixes the issue without introducing an extra variable.

Taken directly from #1621:

In IE8, with a variable everything works as expected:

var t = typeof obj
t === 'function' // false
t === 'object' // true

but without one, things are different:

(typeof obj) === 'function' // true, but SHOULD be false
(typeof obj) === 'object' // true

The extra check outlined above fixes the bug.

like image 108
Etheryte Avatar answered Sep 28 '22 11:09

Etheryte