I am working understanding a JavaScript library and I came across this statement:
const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets)
Then later on in the library, it uses the assetsMannifest
like an object e.g.
assetsManifest['/vendor.js']
I thought the &&
operator was only used to return boolean
values in logical checks. Can someone explain to me what is going on here?
Many thanks,
Clement
I am working understanding a JavaScript library and I came across this statement:
const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets)
Then later on in the library, it uses the assetsMannifest
like an object e.g.
assetsManifest['/vendor.js']
I thought the &&
operator was only used to return boolean
values in logical checks. Can someone explain to me what is going on here?
Many thanks,
Clement
Share Improve this question asked Dec 5, 2016 at 11:58 ClementClement 4,8115 gold badges48 silver badges72 bronze badges 4 |4 Answers
Reset to default 13This operator doesn't always return true
or false
. It doesn't work like in some other programming languages. In JavaScript &&
operator returns the first value if it's falsy or the second one if not.
Examples:
null && 5
returns null
because null
is falsy.
"yeah yeah" && 0
returns 0
because every non-empty string is truthy.
Not so obvious :-)
Further reading:
Why don't logical operators (&& and ||) always return a boolean result?
&& returns first value converting to false
or last value converting to true
. It's because no need to calculate full logical condition with && if first value is falsy
console.log(55 && 66);
console.log(0 && 77);
console.log(88 && 0);
Also you can use &&
or ||
as if
operator:
if (itsSunny) takeSunglasses();
equals to
itsSunny && takeSunglasses();
in that context it is checking if process.env.webpackAssets
is a truthy value. If it is it will evaluate and return the next part. in this case JSON.parse(process.env.webpackAssets)
The logic is essentially
if (process.env.webpackAssets) {
return JSON.parse(process.env.webpackAssets)
}
else {
return process.env.webpackAssets // (null | undefined | 0 | '' | false)
}
Both &&
and ||
are evaluting there arguments in lazy mode and return the last value, after witch the result is known.
123 && (0 || '' && 78) || 7 && 8 || [] && {} || 90 || 77 && 13
###_^^ both results are possible 123 && ???
#_^^ first part is falsy, resume 0 || ??
#####_^^ can't be true, return ''
^^_########## 0 || '' return ''
^^_################ return ''
#######################_^^ resume
#_^^ resume
^^_# return 8
^^_###### return 8
^^_########################## drop
And the result is 8.
1 || false //1
,true && "a" //"a"
– VLAZ Commented Dec 5, 2016 at 12:01