It's not really evaluating a boolean expression and assigning that to token
. What you have there is a kind of shorthand if-else
. Let's break it down:
(req.body && req.body.access_token)
If req.body
is "truthy" (in this particular case it is ensuring that it is not null
or undefined
, probably) then it will assign req.body.access_token
to token
. The expression will short-circuit here and will not proceed.
Otherwise, it looks at the next case:
(req.query && req.query.access_token)
This is the same as the above; except in this case it assigns req.query.access_token
to token
if req.query
is "truthy". It will also short-circuit here unless "falsy".
req.headers['x-access-token'];
This is the final clause. If none of the preceding cases are true, it will assign the value of req.headers['x-access-token']
to token
.
In the traditional form, it would look like this:
var token;
if(req.body && req.body.access_token) {
token = req.body.access_token;
} else if(req.query && req.query.access_token) {
token = req.query.access_token;
} else {
token = req.headers['x-access-token'];
}
What keeps the token from being set to req.body?
The expression is:
var token = req.body && req.body.access_token;
It won't set token
to req.body
. Here, req.body
is kind of acting as a flag. We don't want to do req.body.access_token
directly because req.body
could be null
or undefined
. So what it's doing here is saying "if req.body
is non-null/defined, then assign req.body.access_token
to token
". Realize that if the first term of an &&
is true, the second term must still be evaluated because the only time an AND is true is when both operands are true. However the advantage here is that "evaluating" the second term returns the value of that term as well, which is what set as token
eventually.
More explicitly, the above expression can be represented as:
if(req.body !== null || typeof req.body !== "undefined") {
token = req.body.access_token;
}
But in JavaScript you can simply check if(some_var)
and that won't run the code in the if
block if some_var
is undefined
or null
. But you have to be careful because legitimate values like 0
or an empty-string are "falsy", and you could end up ignoring them.