0

Take a look at the following class "data" method. The method body contains a variable called "result", and is reassigned in the else if clause to an array.

For some reason babel transpiles the aforementioned variable with a leading underscore.

ES6 class:

class Serie {
  constructor( name, data = [] ) {
    Object.defineProperty(this, "name", {
      enumerable: false,
      configurable: false,
      writable: false,
      value: name
    })

    data.map( (v, i) => this[v.name] = v.value );
  }

  data( name ) {
    let result = null;

    if ( arguments.length == 1 ) {
      result = this.hasOwnProperty( name ) ? this[ name ] : result;
    }
    else if ( arguments.length == 0 ) {
      let keys   = Object.keys(this),
          i      = keys.length,
          result = [];

      while ( i-- ) {
        result.push( this[ keys[i] ] );
      }
    }

    return result;
  }

  // ...
}

The transpiled method:

function data(name) {
      var result = null;

      if (arguments.length == 1) {
        result = this.hasOwnProperty(name) ? this[name] : result;
      } else if (arguments.length == 0) {
        var keys = Object.keys(this),
            i = keys.length,
            _result = [];

        while (i--) {
          _result.push(this[keys[i]]);
        }
      }

      return result;
    }
elad.chen
  • 2,375
  • 5
  • 25
  • 37

1 Answers1

2

result is being re-declared, not just reassigned, using let, so scoped to the current block (the else if block).

When transpiled to var, which doesn't adhere to block scoping, the second declaration should not overwrite the first one.

It's basically the difference between this:

let a = 123;
if (true) {
  let a = 456;
}
// a === 123

And this:

var a = 123;
if (true) {
  var a = 456;
}
// a === 456
robertklep
  • 198,204
  • 35
  • 394
  • 381