test code is:
console.log(true && "abc");//abc
who can tell me why the result is abc
?
Boolean. TRUE is a reference to an object of the class Boolean, while true is just a value of the primitive boolean type. Classes like Boolean are often called "wrapper classes", and are used when you need an object instead of a primitive type (for example, if you're storing it in a data structure).
bool "bar" is by default true, but it should be false, it can not be initiliazied in the constructor. is there a way to init it as false without making it static?
Work with Booleans as binary values The byte's low-order bit is used to represent its value. A value of 1 represents true ; a value of 0 represents false .
It can return one of the two values. It returns True if the parameter or value passed is True. It returns False if the parameter or value passed is False.
From MDN (Logical Operators) - Logical And (&&):
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
true
obviously cannot be evaluated to false, so the second value is returned which is "abc".
The &&
operator in JavaScript is somewhat different than in C or Java or etc. It always returns the last evaluated subexpression value (whether the overall expression is true — "truthy" — or false — "falsy") and doesn't force a boolean result. When it fails (when one of the values is "falsy"), then similarly the result is the raw value, and not the value's boolean interpretation.
So it's like this: given A && B
, the interpreter does the following:
false
, then the value of the &&
expression is AV &&
expression.Thus in an if
statement, the &&
expression has the same effect as the boolean-casting operators in C or Java, because the if
statement itself performs a truthy/falsy test on the overall result of the expression. When used by itself however, it's more like, "give me the value of the second expression if it the first is truthy, otherwise give me the value of the first expression".
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