+ 3

typeof with && and ||

Please explain these. Thanks in advance! https://code.sololearn.com/WN3Vh2LXVR0F/?ref=app //undefined console.log(typeof(null)&&typeof(undefined)) //object console.log(typeof(null)||typeof(undefined)) //undefined console.log(typeof(true)&&typeof(undefined)) //boolean console.log(typeof(true)||typeof(undefined)) //object console.log(typeof(true)&&typeof(null)) //boolean console.log(typeof(true)||typeof(null))

17th Jun 2019, 11:37 PM
Heather
Heather - avatar
4 Respostas
+ 6
Heather Another way to look at this is as follows: //Logical AND returns the 2nd operand if both are truthy. Otherwise, it returns a boolean false. console.log( [truthy] && "undefined" ) console.log( [truthy] && "object" ) // Logical OR returns the 1st truthy operand. Otherwise, if both are [falsey], it returns a boolean false. console.log( "object" || [N/A] ) console.log( "boolean" || [N/A] ) console.log( [falsey] || "object" ) console.log( [falsey] || "boolean" ) NOTES: 1. I placed the string value in the examples above to indicate the operand that is returned. 2. Strings with a length greater than 0 are [truthy]. Otherwise, 0 length strings are [falsey]. 3. I placed [N/A] to indicate the operand isn't even evaluated in the Logical OR expressions. I hope this all makes sense.
19th Jun 2019, 4:18 AM
David Carroll
David Carroll - avatar
+ 2
Heather The typeof operator returns a string indicating the type of the unevaluated operand. Thus your lines of code in your post are actually: console.log(string && string) and console.log(string || string) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof And because logical operators convert its operand to boolean true/false and the string is not empty. The lines of code above are in essence console.log(true && true) and console.log(true || true). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators
19th Jun 2019, 2:29 AM
ODLNT
ODLNT - avatar
+ 2
Heather I'm quoting MDN. "Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they will return a non-Boolean value." --MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Description
19th Jun 2019, 3:38 AM
ODLNT
ODLNT - avatar
0
But they don't return true. They return undefined, or object, or boolean.
19th Jun 2019, 2:54 AM
Heather
Heather - avatar