How to return null? when creating a class in javascript

for example, if there is a class whose parameters are invalid when declaring, you should not successfully create an instance but return null,. How to implement it?

in addition, there is another scenario. If I use Array.some to verify an array parameter, how can I make it stop and return null immediately?

// demo: https://7kk7xolr7j.codesandbox.io/
class Foo {
  constructor(props) {
    for (let item in props) {
      try {
        console.log(item);
        if (item < 1) {
          throw new Error(item + " is invalid");
        }
      } catch (e) {
        console.error(e);
        return;
        //  null
      }
    }
  }
}

let testArrA = [1, 1, 1, 0, 0];
let testArrB = [1, 1, 1, 1];
const b = new Foo(testArrB);
const a = new Foo(testArrA);
console.log(b, a); // expected `Foo{} null` but get `Foo{} Foo{}`



Mar.03,2021

as long as new is used, it is impossible to return null .


an exception should be thrown

if the parameter is incorrect.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3c3d3-2c2dd.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3c3d3-2c2dd.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?