Question

Looking between the very first line of code in Bootstrap's minified and unminified JS file, there is an immediate discrepancy:

// bootstrap.js
if (typeof jQuery === 'undefined') { ... }

vs.

// bootstrap.min.js
if("undefined"==typeof jQuery)...

(See for yourself: bootstrap.js and bootstrap.min.js)

I'm confused why this is allowed. My (perhaps naïve) understanding is that === is always a performance gain, and often prevents unexpected results (falsy comparisons with 0 or "", for example). It would seem that the small gains in filesize are lost in performance and potential for erroneous result. Can anyone shed light here?

Was it helpful?

Solution

In the particular code you're citing, it's safe because the types of both operands are invariant, and both are strings. There's no performance savings possible because there'll never need to be any type coercion. Think of == as being something like this:

function ==(a, b) { // obviously this is fake
  if (a === b) return true;
  // type coercion ...
}

Also, personally I think that one should use === over == because of the semantic differences and not because of performance. Micro-optimizations like that aren't important for the vast majority of code most people write. (It's a little ironic in fact that the check for the presence of jQuery is being done with a typeof comparison; that itself is a questionably-valuable micro-optimization.) oops that was wrong :)

OTHER TIPS

typeof will always return a string, so there is no need to worry about type conversion. Ultimately, this doesn't really save much in the file or its execution, but this is considered a safe assumption.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top