Obinwanne Hill Obinwanne Hill - 14 days ago 5
Javascript Question

Using expressions and logical operators in function arguments

What does it mean to have expressions with logical operators passed as an argument to a function?!

For example:

myFunc(expr_1 || expr_2 || expr_3);


Is it equivalent to the following?!:

var expr_all = expr_1 || expr_2 || expr_3;
myFunc(expr_all);


And if so, how is it supposed to work especially if all three expressions evaluate to strings (as opposed to booleans), or if
expr_1
is
undefined
or something?!

Thanks.

Answer

myFunc(expr_1 || expr_2 || expr_3); Is it equivalent to the following?!:

var expr_all = expr_1 || expr_2 || expr_3; myFunc(expr_all);

Yes it is. It will pass the first truthy value to the function.

Truthy values are values that are not false,null,NaN,"", 0,or undefined

This works because || is the logical or statement. It will return the value of the first object from left to right that is truthy. Otherwise it will return false.

See these examples:

"a" || "b" //"a"

"" || "b" //"b"

"" || "" //""

"" || undefined  //undefined

"" || [] // []