Published on

How To Create A Class That Allows Method Chaining In Javascript


One of the things I really liked being able to do in Java was create helper classes where I could easily chain a bunch of methods together to more fluently and easily do something. For example a simple validator class with chaining could be used to validate some inputs and build up a list of errors while it does that for example:

public class Validator {
    private List<String> errors = new LinkedList<String>;

    public Validator isValid(boolean conditionThatShouldBeTrue, String errorMessageIfInvalid) {
    if(!conditionThatShouldBeValid) {
    return this;

    public List<String> getErrors() {
        return errors;


This can then be used as follows:

List<String> validationErrors =
    new Validator()
       .isValid(age >= 18, "You have to be 18 or oder to vote")
       .isValid(surname.trim().length > 0, "Surname is required" )

This makes validating a number of fields easier and more readable as the alternative to this would be multiple if statements.

Doing this in Javascript ended up being quite easy and actually looked very similar to the Java implementation when using the ES6 class syntax:

class Validator {
  errors = []

  isValid(conditionThatMustBeTrue, errorIfInvalid) {
    if (!conditionThatMustBeTrue) {
    return this

  getErrorList() {
    return this.errors

export default Validator

And using it is also almost identical:

validationErrors = new Validator()
  .isValid(age >= 18, 'You have to be 18 or oder to vote')
  .isValid(surname.trim().length > 0, 'Surname is required')