JavaScript is non-strictly typed language as Java,for example.
As we know, it converts value of result dependently upon context:
"2" + "3"
results "23"
"2" * "3"
results 6
This is quite clear and OK for understanding.
I just tried following expressions and got confused:
true && 1
results 1
true || 1
results true
Why the first gives Number and the second gives boolean?
Considering JavaScript conversion rules,I expect to get boolean
values in both cases,due to boolean
context of expression.
In programming, type conversion is the process of converting data of one type to another. For example: converting String data to Number . There are two types of type conversion in JavaScript.
The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true'); For a more case insensitive approach, try: let myBool = (myString.
We can use Number() function in JavaScript to convert a value to a Number. It can convert any numerical text and boolean value to a Number. In case of strings of non-numbers it will convert it to a NaN(Not a Number).
To convert a string to a boolean, use the strict equality operator to compare the string to the string "true" , e.g. const bool = str === 'true' . If the condition is met, the strict equality operator will return the boolean value true , otherwise false is returned. Copied!
Check Douglas Crockford's site, it says:
The && operator is commonly called logical and. It can also be called guard. If the first operand is false, null, undefined, "" (the empty string), or the number 0 then it returns the first operand. Otherwise, it returns the second operand. This provides a convenient way to write a null-check:
var value = p && p.name; /* The name value will only be retrieved from
p if p has a value, avoiding an error. */
The || operator is commonly called logical or. It can also be called default. If the first operand is false, null, undefined, "" (the empty string), or the number 0, then it returns the second operand. Otherwise, it returns the first operand. This provides a convenient way to specify default values:
value = v || 10; /* Use the value of v, but if v doesn't have a value,
use 10 instead. */
To quote MDC;
&&; 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.
||; Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
So in the first example, 1
is being returned because expr1
cannot be converted to false.
In the second example, true
can be converted to true, so it's returned.
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