0

Is there a standard way to return "Option" (an object that may be null) in Javascript?

For example, is there a more standard way to handle a piece of code like this, especially the function GetById(userId)?

class User {
  static function GetById(userId) {
    if (userId === 'A_GOOD_ID') {
        return new User('GOOD_NAME');
    }
    return null;
  }

  constructor(name) {
    this.name = name;
  }
}

function authenticate(userId) {
  const user = User.GetById(userId);
  if (user) return true;
  return false;
}
Man-Kit Yau
  • 149
  • 1
  • 10
  • `return !!(User.GetById(userId));`? In general you can deal with false-y values using [logical operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators) and [the conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator). – jonrsharpe May 06 '19 at 08:00
  • 1
    `if (user)` is the standard way. Need to take care if you want to accept falsey things like `0`, but otherwise works and is very concise. – Thilo May 06 '19 at 08:00
  • Possible duplicate of [Is there a standard function to check for null, undefined, or blank variables in JavaScript?](https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in) – Thilo May 06 '19 at 08:01

2 Answers2

2

That's the standard way, returning null is preferable rather than, for example, throwing an error.

When you use the function, you should check if the returned value is truthy:

const result = User.GetById(...);
if (!result) {
  // handle error
}

Or you can use the shorthand or:

User.GetById(...) || handleError();

which is less readable, in the opinion of many.

0

You can try using the conditional operator expression ? value_if_true : value_if_false for a more concise code. For example:

static function GetById(userID) {
    return userId === 'A_GOOD_ID' ? new User('GOOD_NAME') : null;
}

Or even shorter:

static function GetById((userID) => userID === 'A_GOOD_ID' ? new User('GOOD_NAME') : null;

The same applies for your authenticate function:

return user ? true : false;

As for checking using if (user), it's a pretty standard way to check if an expression is truth-y or not false-y.

Richard
  • 7,037
  • 2
  • 23
  • 76