Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Javascript minifiers convert === to ==?

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?

like image 662
Impirator Avatar asked May 07 '14 18:05

Impirator


1 Answers

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 :)

like image 62
Pointy Avatar answered Oct 03 '22 14:10

Pointy