Home » Javascript » Why doesn't the google closure compile keep reused indexes in variables?

Why doesn't the google closure compile keep reused indexes in variables?

Posted by: admin August 19, 2018 Leave a comment

Questions:

This MWE shows how the google closure compiler exchanges the short obj[keyA] for the longer obj["some-very-long-key"]:

Input javascript:

var foo = new function() {
  var keyA = 'some-very-long-key';
  var keyB = 'another-key';
  this.bar = function() {
    obj[keyA] = {};
  }
  this.baz = function(data) {
    obj[keyA][keyB] = data;
  }
}();

Google closure compiler output:

var foo = new function() {
  this.bar = function() {
    obj["some-very-long-key"] = {};
  };
  this.baz = function(a) {
    obj["some-very-long-key"]["another-key"] = a;
  };
};

If I remove the wrapping function, it works as I expected it to:

Input javascript:

var keyA = 'some-very-long-key';
var keyB = 'another-key';
function bar() {
  obj[keyA] = {};
}
function baz(data) {
  obj[keyA][keyB] = data;
}

Google closure compiler output:

var keyA = "some-very-long-key", keyB = "another-key";
function bar() {
  obj[keyA] = {};
}
function baz(a) {
  obj[keyA][keyB] = a;
}
;

Because I use a long key quite often in my project, the code gets larger than it could be, if google closure compiler kept the string literal in the variable.

  • What causes this behaviour?
  • How can I get it to store the string literal inside a variable and use that variable (which has a shorter name) as index, whilst keeping the whole thing inside a constructor?

Update 1: I know that my wanted result might perform ever so slightly worse, but I’d rather take the much shorter code.

Answers: