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
This 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 string is truthy.
Not so obvious :-)
Further reading:
Why don't logical operators (&& and ||) always return a boolean result?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With