0

I want to prevent the constructor from instantiating new object, if an argument is not provided.Also in that case i like to return null. But the constructor is creating an object instance even thought i'm returning null.

class SampleClass {
  constructor(someArg){
    if(someArg){
      return new SampleClass();
    }
    else{
      return null;
    }
  }
}

const sampleClass = new SampleClass();
console.log(sampleClass);

1 Answers1

2

You can't do that; a constructor can't return null. See What values can a constructor return to avoid returning this?.

What you can do is create a factory method that will return null. See below. Your question shows you ignoring the argument if it's provided but I assumed you'd want to use it, so I made that change. See below.

class SampleClass {
  constructor(someArg){
    this.someArg = someArg;
  }

  static create(someArg) {
    return (someArg) ? new SampleClass(someArg) : null;
  }
}

const willBeNull = SampleClass.create();
console.log(willBeNull);
const willNotBeNull = SampleClass.create("foo");
console.log(willNotBeNull);

You can also throw an error, as some commenters suggested:

class SampleClass {
  constructor(someArg){
    if (!someArg) throw new TypeError("an argument is required");
    this.someArg = someArg;
  }
}

const sampleClass = new SampleClass("foo");
console.log(sampleClass);
try {
  const willError = new SampleClass();
  // below console.log will not be reached
  console.log(willError);
} catch(e) {
  // instead we will catch the error here
  console.log(e.stack);
}
David P. Caldwell
  • 3,394
  • 1
  • 19
  • 32
  • I'd recommend to combine both approaches: throw an error in the constructor, *and* add a null-returning factory function. (The only problem with this is the duplicated validation logic). – Bergi Dec 30 '20 at 16:30