Infinite loops in ES6 Classes: pinky key to the rescue!

Francis Pham
2 min readSep 16, 2015

--

Who woulda thunk the underscore key ‘_’ can help prevent an infinite loop when using classes in ES6?

ES6 enables getter & setter methods for classes. However in ES6, the properties’ names must NOT be the same as the method names. Note that in ES5, the properties’ names and method names can be the same, although you may not get the behavior that you want. The reason why naming matters is because of the way ES6 implements getting & setting properties.

For example, assume you have a guy object created from the Person class in ES6 with a name property. If you have both a property called name and method called name, then an infinite loop will occur because instead of getting or setting the properties directly like an object literal (guy.name), ES6 actually CALLS the getter/ setter methods instead (guy.name()). The exact error message ES6 will give you is “maximum stack calls exceeded”.

class Person { // ES6 example

constructor(name) {

this.name = name;

}

get name() {

return this.name;

} // since ES6 calls name() for this.name, an infinite loop will occur;

}

function Person(name) { // ES5 example

this.name = name;

}

Person.prototype.name = function() {

return this.name;

}; // in ES5, since name property is defined in Person class, the name function in the prototype is never called; a TypeError (not a function) is thrown if name() is called

A conventional solution to prevent the infinite loop in ES6 is to simply prefix the property name by ‘_’. Although the ‘_’ character typically implies a private property, this.property is NOT private for classes in ES6; instead properties are public in ES6 by default. This is why I originally did not use ‘_’ to prefix properties and ran into the infinite loop that took me an hour to debug! So just use the ‘_’ or some other character to prefix property names to prevent infinite loops when using classes in ES6.

--

--