Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript && Operator used for returns

Tags:

javascript

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

like image 311
Clement Avatar asked Dec 05 '16 11:12

Clement


1 Answers

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?

like image 137
Krzysztof Dąbrowski Avatar answered Sep 28 '22 12:09

Krzysztof Dąbrowski