Logical OR in combination with lodash get() gives weird results

OK, so I can’t wrap my head around this…

I need to find a bankScheme and there is some code before this snippet that might find it so I have set it to ABC to illustrate that the value was found. If it still wasn’t found I wanted to try to find it from some other data, object j in the snippet below but as object j might not contain PaymentMeans I used the lodash _.get() to fetch the value (in the real object the path is much “deeper”).

const _ = require('lodash');

let j = { PaymentMeans: '12' };
let bankScheme = 'ABC';
// Let's try the OR operand with a lodash function:
bankScheme = bankScheme || _.get(j, 'PaymentMeans') === '58' ? '58Found' : '58NotFound';

console.log(_.get(j, 'PaymentMeans'), bankScheme);
// It now logs '12 58Found' which is very weird as it should log 'ABC' in any case, and even if it didn't find 'ABC' it should log '58NotFound'...
// If however bankScheme = null then the _.get() works as expected

The weird thing here is, firstly, that the logical OR (||) is not doing what I would expect it to, and that is to leave the value as ABC as it is not “falsy” to begin with.

Secondly, if we accept that the OR is not working, the return should be 58NotFound but now it is 58Found

What am I missing?

Writing it as this works as expceted though:

bankScheme = bankScheme ? bankScheme : _.get(j, 'PaymentMeans') === '58' ? '58Found' : '58NotFound';

Code: https://repl.it/join/hjqoaatb-anderswa


Don’t forget about the operator priority.


bankScheme = bankScheme || _.get(j, 'PaymentMeans') === '58' ? '58Found' : '58NotFound';

is equivalent to this:

bankScheme = (bankScheme || _.get(j, 'PaymentMeans') === '58') ? '58Found' : '58NotFound';

Leave a Reply

Your email address will not be published. Required fields are marked *