Skip to content

Instantly share code, notes, and snippets.

@paulrobertlloyd
Last active January 1, 2016 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulrobertlloyd/8189506 to your computer and use it in GitHub Desktop.
Save paulrobertlloyd/8189506 to your computer and use it in GitHub Desktop.
grunt-contrib-uglify is borking my JavaScript. What am I doing wrong?
/**
* Before grunt-contrib-uglify
*/
(function(doc) {
if (document.querySelector) {
var toggleClassName = function(element, toggleClass) {
var reg = new RegExp('(\\s|^)' + toggleClass + '(\\s|$)');
if (!element.className.match(reg)) {
element.className += ' ' + toggleClass;
} else {
element.className = element.className.replace(reg, '');
}
};
doc.querySelector('a[href="#navigation"]').addEventListener('click', function(e) {
e.preventDefault();
toggleClassName(doc.body, 'js-menu-active');
});
}
}(this.document));
/**
* After grunt-contrib-uglify (mangle:false, beautify:true)
*/
!function(doc) {
if (document.querySelector) {
var toggleClassName = function(element, toggleClass) {
var reg = new RegExp("(\\s|^)" + toggleClass + "(\\s|$)");
element.className.match(reg) ? element.className = element.className.replace(reg, "") : element.className += " " + toggleClass;
};
doc.querySelector('a[href="#navigation"]').addEventListener("click", function(e) {
e.preventDefault(), toggleClassName(doc.body, "js-menu-active");
});
}
}(this.document);
@jackfranklin
Copy link

Still debugging, but just to explain this line for you:

element.className.match(reg) ? element.className = element.className.replace(reg, "") : element.className += " " + toggleClass;

Firstly, let's break that down onto lines:

element.className.match(reg) 
  ? element.className = element.className.replace(reg, "")
  : element.className += " " + toggleClass;

This is a ternary operator. It's basically a shorthand for a conditional. These two are equivalent:

if(a) {
  doSomething();
} else {
  doOtherThing();
}
a ? doSomething() : doOtherThing();

Those two are the same. Uglify is rewriting the conditional just to save room (and hence bytes), I imagine. The only other thing it's doing is reversing the conditional. You have:

if(!foo) { something() } else { someOtherThing(); }

And it's doing this:

if(foo) { someOtherThing(); } else { something() }
// and then:
foo ? someOtherThing() : something()

HTH.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment