javascript - How does using logic operators populate a var? -


this question has answer here:

let's take @ code:

var token = (req.body && req.body.access_token) ||             (req.query && req.query.access_token) ||             req.headers['x-access-token']; 

taken here.

shouldn't return boolean? confuses me chained , and or statements. i'm reading as:

the variable token equals boolean whether req.body , req.body.access_token exist. or, if don't exist, equals boolean whether req.query , req.query.access_token exist. or, if don't exist, equals value of req.headers['x-access-token'].

furthermore, if analyze piece:

var token = req.body && req.body.access_token; 

what keeps token being set req.body?

it's not evaluating boolean expression , assigning token. have there kind of shorthand if-else. let's break down:

(req.body && req.body.access_token) 

if req.body "truthy" (in particular case ensuring not null or undefined, probably) assign req.body.access_token token. expression short-circuit here , not proceed.

otherwise, looks @ next case:

(req.query && req.query.access_token) 

this same above; except in case assigns req.query.access_token token if req.query "truthy". short-circuit here unless "falsy".

req.headers['x-access-token']; 

this final clause. if none of preceding cases true, assign value of req.headers['x-access-token'] token.

in traditional form, 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 token being set req.body?

the expression is:

var token = req.body && req.body.access_token; 

it won't set token req.body. here, req.body kind of acting flag. don't want req.body.access_token directly because req.body null or undefined. it's doing here saying "if req.body non-null/defined, assign req.body.access_token token". realize if first term of && true, second term must still evaluated because time , true when both operands true. advantage here "evaluating" second term returns value of term well, set token eventually.

more explicitly, above expression can represented as:

if(req.body !== null || typeof req.body !== "undefined") {     token = req.body.access_token; } 

but in javascript can check if(some_var) , won't run code in if block if some_var undefined or null. have careful because legitimate values 0 or empty-string "falsy", , end ignoring them.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -