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.
This operator performs logical conjunction on two Boolean expressions. If both expressions evaluate to True, the AND operator returns True. If either or both expressions evaluate to False, the AND operator returns False.
You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0 . You can use arguments.length to count how many arguments the function was called with.
In mathematics, an argument of a function is a value provided to obtain the function's result. It is also called an independent variable. For example, the binary function has two arguments, and , in an ordered pair . The hypergeometric function is an example of a four-argument function.
There are five logical operator symbols: tilde, dot, wedge, horseshoe, and triple bar. Tilde is the symbol for negation.
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
"" || [] // []
||
isn't a comparison operator. It is a shorthand conditional. If the expression on the left evaluates to true then it is returned, otherwise the expression on the right is returned.
If an undefined variable is evaluated before the evaluation completes: undefinedVar || 3
then the entire evaluation fails and an error occurs.
Your 2 code samples are equivalent.
They're equivalent (if you ignore the intermediate variable).
JavaScript's logical OR operator short-circuits, so it'll break at the first truthy value in that chain of ORs and return it. If none of them are truthy, the last one will be returned.
Truthy values are the opposite of falsy values, which are 0
, ''
, false
, null
, undefined
, etc. If one of those variables happens to be 0
, you may run into problems.
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