0

I have the following statement which I'd like to have return any of these values if they are set, otherwise just return null.

var token = request.body.token || request.query.token || request.headers['x-access-token'];

However, whenever one of these is not set it throws a TypeError exception (cannot read property of undefined).

I thought something like this might be the solution but it's throwing the same exception:

var token = (typeof request.body.token === 'undefined') ? null : request.body.token || (typeof request.query.token === 'undefined') ? null :  request.query.token || (typeof request.headers['x-access-token'] === 'undefined') ? null : request.headers['x-access-token'];

Can someone suggest a better way of achieving this?

Seonixx
  • 468
  • 3
  • 16
  • First you need to be sure that both `request` and `request.body` are defined. – pawel Oct 28 '15 at 13:48
  • Well if I knew that for sure then I wouldn't have this problem. I need to test whether they exist and return null if they don't. – Seonixx Oct 28 '15 at 13:49
  • Yeah, but you're checking for `request.body.token` right away while either `request` or `request.body` may be undefined. – pawel Oct 28 '15 at 13:51
  • `var token = request.body ? request.body.token : '' || request.query ? request.query.token : '' || request.headers ? request.headers['x-access-token'] : undefined;` – Tushar Oct 28 '15 at 13:55

1 Answers1

3

cannot read property of undefined

That means that when you have a.b.c it is either a or b that is undefined, not c, so you can't test the definedness of c.

Can someone suggest a better way of achieving this?

Avoid ternary operators for complex sets of tests. Go back to using if and multiple lines. It will be easier to read, write and maintain.

var token;
if (request) { // In a separate `if` because it is common to all the tests
    if (request.body && request.body.token) {
        token = request.body.token;
    } else if (request.query && request.query.token) {
        token = request.query.token;
    } else if (request.headers && request.headers['x-access-token']) {
        token = request.headers['x-access-token'];
    }
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335