Related
Why do these logical operators return an object and not a boolean?
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
var _ = obj && obj._;
I want to understand why it returns result of obj.fn() (if it is defined) OR obj._ but not boolean result.
In JavaScript, both || and && are logical short-circuit operators that return the first fully-determined “logical value” when evaluated from left to right.
In expression X || Y, X is first evaluated, and interpreted as a boolean value. If this boolean value is “true”, then it is returned. And Y is not evaluated. (Because it doesn’t matter whether Y is true or Y is false, X || Y has been fully determined.) That is the short-circuit part.
If this boolean value is “false”, then we still don’t know if X || Y is true or false until we evaluate Y, and interpret it as a boolean value as well. So then Y gets returned.
And && does the same, except it stops evaluating if the first argument is false.
The first tricky part is that when an expression is evaluated as “true”, then the expression itself is returned. Which counts as "true" in logical expressions, but you can also use it. So this is why you are seeing actual values being returned.
The second tricky part is that when an expression is evaluated as “false”, then in JS 1.0 and 1.1 the system would return a boolean value of “false”; whereas in JS 1.2 on it returns the actual value of the expression.
In JS false, 0, -0, "", null, undefined, NaN and document.all all count as false.
Here I am of course quoting logical values for discussion’s sake. Of course, the literal string "false" is not the same as the value false, and is therefore true.
In the simplest terms:
The || operator returns the first truthy value, and if none are truthy, it returns the last value (which is a falsy value).
The && operator returns the first falsy value, and if none are falsy, it return the last value (which is a truthy value).
It's really that simple. Experiment in your console to see for yourself.
console.log("" && "Dog"); // ""
console.log("Cat" && "Dog"); // "Dog"
console.log("" || "Dog"); // "Dog"
console.log("Cat" || "Dog"); // "Cat"
var _ = ((obj.fn && obj.fn() ) || obj._ || ( obj._ == {/* something */}))? true: false
will return boolean.
UPDATE
Note that this is based on my testing. I am not to be fully relied upon.
It is an expression that does not assign true or false value. Rather it assigns the calculated value.
Let's have a look at this expression.
An example expression:
var a = 1 || 2;
// a = 1
// it's because a will take the value (which is not null) from left
var a = 0 || 2;
// so for this a=2; //its because the closest is 2 (which is not null)
var a = 0 || 2 || 1; //here also a = 2;
Your expression:
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
// _ = closest of the expression which is not null
// in your case it must be (obj.fn && obj.fn())
// so you are gettig this
Another expression:
var a = 1 && 2;
// a = 2
var a = 1 && 2 && 3;
// a = 3 //for && operator it will take the fartest value
// as long as every expression is true
var a = 0 && 2 && 3;
// a = 0
Another expression:
var _ = obj && obj._;
// _ = obj._
In most programming languages, the && and || operators returns boolean. In JavaScript it's different.
OR Operator:
It returns the value of the first operand that validates as true (if any), otherwise it returns the value of the last operand (even if it validates as false).
Example 1:
var a = 0 || 1 || 2 || 3;
^ ^ ^ ^
f t t t
^
first operand that validates as true
so, a = 1
Example 2:
var a = 0 || false || null || '';
^ ^ ^ ^
f f f f
^
no operand validates as true,
so, a = ''
AND Operator:
It returns the value of the last operand that validates as true (if all conditions validates as true), otherwise it returns the value of the first operand that validates as false.
Example 1:
var a = 1 && 2 && 3 && 4;
^ ^ ^ ^
t t t t
^
last operand that validates as true
so, a = 4
Example 2:
var a = 2 && '' && 3 && null;
^ ^ ^ ^
t f t f
^
return first operand that validates as false,
so, a = ''
Conclusion:
If you want JavaScript to act the same way how other programming languages work, use Boolean() function, like this:
var a = Boolean(1 || 2 || 3);// a = true
You should think of the short-circuit operators as conditionals rather than logical operators.
x || y roughly corresponds to:
if ( x ) { return x; } else { return y; }
and x && y roughly corresponds to:
if ( x ) { return y; } else { return x; }
Given this, the result is perfectly understandable.
From MDN documentation:
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.
And here's the table with the returned values of all logical operators.
I think you have basic JavaScript methodology question here.
Now, JavaScript is a loosely typed language. As such, the way and manner in which it treats logical operations differs from that of other standard languages like Java and C++. JavaScript uses a concept known as "type coercion" to determine the value of a logical operation and always returns the value of the first true type. For instance, take a look at the code below:
var x = mystuff || document;
// after execution of the line above, x = document
This is because mystuff is an a priori undefined entity which will always evaluate to false when tested and as such, JavaScript skips this and tests the next entity for a true value. Since the document object is known to JavaScript, it returns a true value and JavaScript returns this object.
If you wanted a boolean value returned to you, you would have to pass your logical condition statement to a function like so:
var condition1 = mystuff || document;
function returnBool(cond){
if(typeof(cond) != 'boolean'){ //the condition type will return 'object' in this case
return new Boolean(cond).valueOf();
}else{ return; }
}
// Then we test...
var condition2 = returnBool(condition1);
window.console.log(typeof(condition2)); // outputs 'boolean'
We can refer to the spec(11.11) of JS here of:
Semantics
The production LogicalANDExpression :LogicalANDExpression &&BitwiseORExpression is evaluated as follows:
Evaluate LogicalANDExpression.
2.Call GetValue(Result(1)).
3.Call ToBoolean(Result(2)).
4.If Result(3) is false, return Result(2).
5.Evaluate BitwiseORExpression.
6.Call GetValue(Result(5)).
7.Return Result(6).
see here for the spec
First, it has to be true to return, so if you are testing for truthfulness then it makes no difference
Second, it lets you do assignments along the lines of:
function bar(foo) {
foo = foo || "default value";
Compare:
var prop;
if (obj.value) {prop=obj.value;}
else prop=0;
with:
var prop=obj.value||0;
Returning a truthy expression - rather than just true or false - usually makes your code shorter and still readable. This is very common for ||, not so much for &&.
Why do these logical operators return an object and not a boolean?
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
var _ = obj && obj._;
I want to understand why it returns result of obj.fn() (if it is defined) OR obj._ but not boolean result.
In JavaScript, both || and && are logical short-circuit operators that return the first fully-determined “logical value” when evaluated from left to right.
In expression X || Y, X is first evaluated, and interpreted as a boolean value. If this boolean value is “true”, then it is returned. And Y is not evaluated. (Because it doesn’t matter whether Y is true or Y is false, X || Y has been fully determined.) That is the short-circuit part.
If this boolean value is “false”, then we still don’t know if X || Y is true or false until we evaluate Y, and interpret it as a boolean value as well. So then Y gets returned.
And && does the same, except it stops evaluating if the first argument is false.
The first tricky part is that when an expression is evaluated as “true”, then the expression itself is returned. Which counts as "true" in logical expressions, but you can also use it. So this is why you are seeing actual values being returned.
The second tricky part is that when an expression is evaluated as “false”, then in JS 1.0 and 1.1 the system would return a boolean value of “false”; whereas in JS 1.2 on it returns the actual value of the expression.
In JS false, 0, -0, "", null, undefined, NaN and document.all all count as false.
Here I am of course quoting logical values for discussion’s sake. Of course, the literal string "false" is not the same as the value false, and is therefore true.
In the simplest terms:
The || operator returns the first truthy value, and if none are truthy, it returns the last value (which is a falsy value).
The && operator returns the first falsy value, and if none are falsy, it return the last value (which is a truthy value).
It's really that simple. Experiment in your console to see for yourself.
console.log("" && "Dog"); // ""
console.log("Cat" && "Dog"); // "Dog"
console.log("" || "Dog"); // "Dog"
console.log("Cat" || "Dog"); // "Cat"
var _ = ((obj.fn && obj.fn() ) || obj._ || ( obj._ == {/* something */}))? true: false
will return boolean.
UPDATE
Note that this is based on my testing. I am not to be fully relied upon.
It is an expression that does not assign true or false value. Rather it assigns the calculated value.
Let's have a look at this expression.
An example expression:
var a = 1 || 2;
// a = 1
// it's because a will take the value (which is not null) from left
var a = 0 || 2;
// so for this a=2; //its because the closest is 2 (which is not null)
var a = 0 || 2 || 1; //here also a = 2;
Your expression:
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
// _ = closest of the expression which is not null
// in your case it must be (obj.fn && obj.fn())
// so you are gettig this
Another expression:
var a = 1 && 2;
// a = 2
var a = 1 && 2 && 3;
// a = 3 //for && operator it will take the fartest value
// as long as every expression is true
var a = 0 && 2 && 3;
// a = 0
Another expression:
var _ = obj && obj._;
// _ = obj._
In most programming languages, the && and || operators returns boolean. In JavaScript it's different.
OR Operator:
It returns the value of the first operand that validates as true (if any), otherwise it returns the value of the last operand (even if it validates as false).
Example 1:
var a = 0 || 1 || 2 || 3;
^ ^ ^ ^
f t t t
^
first operand that validates as true
so, a = 1
Example 2:
var a = 0 || false || null || '';
^ ^ ^ ^
f f f f
^
no operand validates as true,
so, a = ''
AND Operator:
It returns the value of the last operand that validates as true (if all conditions validates as true), otherwise it returns the value of the first operand that validates as false.
Example 1:
var a = 1 && 2 && 3 && 4;
^ ^ ^ ^
t t t t
^
last operand that validates as true
so, a = 4
Example 2:
var a = 2 && '' && 3 && null;
^ ^ ^ ^
t f t f
^
return first operand that validates as false,
so, a = ''
Conclusion:
If you want JavaScript to act the same way how other programming languages work, use Boolean() function, like this:
var a = Boolean(1 || 2 || 3);// a = true
You should think of the short-circuit operators as conditionals rather than logical operators.
x || y roughly corresponds to:
if ( x ) { return x; } else { return y; }
and x && y roughly corresponds to:
if ( x ) { return y; } else { return x; }
Given this, the result is perfectly understandable.
From MDN documentation:
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.
And here's the table with the returned values of all logical operators.
I think you have basic JavaScript methodology question here.
Now, JavaScript is a loosely typed language. As such, the way and manner in which it treats logical operations differs from that of other standard languages like Java and C++. JavaScript uses a concept known as "type coercion" to determine the value of a logical operation and always returns the value of the first true type. For instance, take a look at the code below:
var x = mystuff || document;
// after execution of the line above, x = document
This is because mystuff is an a priori undefined entity which will always evaluate to false when tested and as such, JavaScript skips this and tests the next entity for a true value. Since the document object is known to JavaScript, it returns a true value and JavaScript returns this object.
If you wanted a boolean value returned to you, you would have to pass your logical condition statement to a function like so:
var condition1 = mystuff || document;
function returnBool(cond){
if(typeof(cond) != 'boolean'){ //the condition type will return 'object' in this case
return new Boolean(cond).valueOf();
}else{ return; }
}
// Then we test...
var condition2 = returnBool(condition1);
window.console.log(typeof(condition2)); // outputs 'boolean'
We can refer to the spec(11.11) of JS here of:
Semantics
The production LogicalANDExpression :LogicalANDExpression &&BitwiseORExpression is evaluated as follows:
Evaluate LogicalANDExpression.
2.Call GetValue(Result(1)).
3.Call ToBoolean(Result(2)).
4.If Result(3) is false, return Result(2).
5.Evaluate BitwiseORExpression.
6.Call GetValue(Result(5)).
7.Return Result(6).
see here for the spec
First, it has to be true to return, so if you are testing for truthfulness then it makes no difference
Second, it lets you do assignments along the lines of:
function bar(foo) {
foo = foo || "default value";
Compare:
var prop;
if (obj.value) {prop=obj.value;}
else prop=0;
with:
var prop=obj.value||0;
Returning a truthy expression - rather than just true or false - usually makes your code shorter and still readable. This is very common for ||, not so much for &&.
Why if I write the below script the value of variable f is 2016 ?
var year = 2016;
var g = 'foo';
var f = typeof g != 'undefined' && year;
Because && is a very interesting operator in JavaScript: Unlike some other languages, it doesn't result in true or false (necessarily). Instead, the result of && is the value of its left operand if that's falsy,1 or the value of its right operand otherwise.
It works like this:
Evaluate the left-hand operand (in your case, typeof g != 'undefined').
If that value is falsy, that's the result of the operation and we stop here.
If that value is truthy,2 evaluate the right-hand operand (year) and make that the result of the operation.
Following it through for your example:
Evaluate typeof g != 'undefined'. Since typeof g is 'string', and 'string' != 'undefined', that's true.
true is not falsy so we don't stop.
Evaluate year and make that the result.
So f gets 2016 (the value of year) assigned to it.
&& has an equally-interesting cousin, ||, on which I've written a blog post about this behavior: JavaScript's Curiously-Powerful OR Operator (||)
1 Falsy values are values that coerce to false when treated as booleans. The falsy values are 0, "", NaN, null, undefined, and of course `false.
2 Truthy values are values that aren't falsy (they coerce true when treated like a boolean).
Note: The way values act when you use them as booleans is not the same way they behave if you compare them to booleans. "foo" is a truthy value, but "foo" == true and "foo" === true are both false.
Yes, the value of f will be 2016.
Let's break down your code.
typeof g != 'undefined' //returns true
In the case of logical operator, the final value will be returned. In your case
true && year //returns 2016
As the && is satisfied, the final value(year) will b returned and assigned to f
The && operator always returns the last thing it tested, and because in your case that's year, it will return the value of year.
The && never converts variables into booleans, it only checks if it's a truthy value.
The && operator evaluates to its left argument if that is falsey, otherwise it evaluates to its right argument.
Since g is not undefined, typeof g != 'undefined' is true, typeof g != 'undefined' && year evaluates to year which is 2016.
(This differs from some other languages, where the result of logical operators like && or || will always be a boolean, but this is not the case with JavaScript.)
What's the difference between | and || in Javascript?
Furthermore, what's the difference between & and &&?
| is a bitwise or, || is a logical or.
A bitwise or takes the two numbers and compares them on a bit-by-bit basis, producing a new integer which combines the 1 bits from both inputs. So 0101 | 1010 would produce 1111.
A logical or || checks for the "truthiness" of a value (depends on the type, for integers 0 is false and non-zero is true). It evaluates the statement left to right, and returns the first value which is truthy. So 0101 || 1010 would return 0101 which is truthy, therefore the whole statement is said to be true.
The same type of logic applies for & vs &&. 0101 & 1010 = 0000. However 0101 && 1010 evaluates to 1010 (&& returns the last truthy value so long as both operands are truthy).
& is the bitwise AND operator
| is the bitwise OR operator
&& is the logical AND operator
|| is the logical OR operator
The difference is that logical operators only consider each input at face value, treating them as whole, while bitwise operators work at the bit level:
var thetruth = false;
var therest = true;
var theuniverse = thetruth && therest; //false
var theparallel = thetruth && thetruth; //true
var theindifferent = thetruth || therest; //true
var theideal = thetruth || thetruth; // false
var thematrix = 5346908590;
var mrsmith = 2354656767;
var theoracle = thematrix & mrsmith; //202445230
var theone = thematrix | mrsmith; //7499120127
Another difference is that || uses shortcut evaluation. That is, it only evaluates the right side if the left side is false (or gets converted to false in a boolean context, e.g. 0, "", null, etc.). Similarly, && only evaluates the right side if the left side is true (or non-zero, non-empty string, an object, etc.). | and & always evaluate both sides because the result depends on the exact bits in each value.
The reasoning is that for ||, if either side is true, the whole expression is true, so there's no need to evaluate any further. && is the same but reversed.
The exact logic for || is that if the left hand side is "truthy", return that value (note that it is not converted to a boolean), otherwise, evaluate and return the right hand side. For &&, if the left hand side is "falsey", return it, otherwise evaluate and return the right hand side.
Here are some examples:
false && console.log("Nothing happens here");
true || console.log("Or here");
false || console.log("This DOES get logged");
"foo" && console.log("So does this");
if (obj && obj.property) // make sure obj is not null before accessing a property
To explain a little more in layman's terms:
&& and || are logical operators. This means they're used for logical comparison;
if (a == 4 && b == 5)
This means "If a equals to four AND b equals to five"
| and & are bitwise operators. They operate on bits in a specific fashion which the wiki article explains in detail:
http://en.wikipedia.org/wiki/Bitwise_operation
In Javascript perspective, there is more to it.
var a = 42;
var b = "abc";
var c = null;
a || b; // 42
a && b; // "abc"
c || b; // "abc"
c && b; // null
Both || and && operators perform a boolean test on the first operand (a or c). If the operand is not already boolean (as it's not, here), a normal ToBoolean coercion occurs, so that the test can be performed.
For the || operator, if the test is true, the || expression results in the value of the first operand (a or c). If the test is false, the || expression results in the value of the second operand (b).
Inversely, for the && operator, if the test is true, the && expression results in the value of the second operand (b). If the test is false, the && expression results in the value of the first operand (a or c).
The result of a || or && expression is always the underlying value of one of the operands, not the (possibly coerced) result of the test. In c && b, c is null, and thus falsy. But the && expression itself results in null (the value in c), not in the coerced false used in the test.
Single | is bit wise OR operator .
If you do 2 | 3 , it converts to binary and performs OR operation.
01
11
Results in 11 equal to 3.
Where as || operator checks if first argument is true, if it is true it returns else it goes to other operator.
2 || 3 returns 2 since 2 is true.
one more point i want to add is || operator is used to assign default value in case the value you are assigning is undefined. So for Exapmle you are assigning a obj to some object test and if you dont want test to be undefined then you can do the following to ensure that value of test wont be undefined.
var test = obj || {};
so in case obj is undefined then test's value will be empty object.
So it is also being used for assigning default value to your object.
Why do these logical operators return an object and not a boolean?
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
var _ = obj && obj._;
I want to understand why it returns result of obj.fn() (if it is defined) OR obj._ but not boolean result.
In JavaScript, both || and && are logical short-circuit operators that return the first fully-determined “logical value” when evaluated from left to right.
In expression X || Y, X is first evaluated, and interpreted as a boolean value. If this boolean value is “true”, then it is returned. And Y is not evaluated. (Because it doesn’t matter whether Y is true or Y is false, X || Y has been fully determined.) That is the short-circuit part.
If this boolean value is “false”, then we still don’t know if X || Y is true or false until we evaluate Y, and interpret it as a boolean value as well. So then Y gets returned.
And && does the same, except it stops evaluating if the first argument is false.
The first tricky part is that when an expression is evaluated as “true”, then the expression itself is returned. Which counts as "true" in logical expressions, but you can also use it. So this is why you are seeing actual values being returned.
The second tricky part is that when an expression is evaluated as “false”, then in JS 1.0 and 1.1 the system would return a boolean value of “false”; whereas in JS 1.2 on it returns the actual value of the expression.
In JS false, 0, -0, "", null, undefined, NaN and document.all all count as false.
Here I am of course quoting logical values for discussion’s sake. Of course, the literal string "false" is not the same as the value false, and is therefore true.
In the simplest terms:
The || operator returns the first truthy value, and if none are truthy, it returns the last value (which is a falsy value).
The && operator returns the first falsy value, and if none are falsy, it return the last value (which is a truthy value).
It's really that simple. Experiment in your console to see for yourself.
console.log("" && "Dog"); // ""
console.log("Cat" && "Dog"); // "Dog"
console.log("" || "Dog"); // "Dog"
console.log("Cat" || "Dog"); // "Cat"
var _ = ((obj.fn && obj.fn() ) || obj._ || ( obj._ == {/* something */}))? true: false
will return boolean.
UPDATE
Note that this is based on my testing. I am not to be fully relied upon.
It is an expression that does not assign true or false value. Rather it assigns the calculated value.
Let's have a look at this expression.
An example expression:
var a = 1 || 2;
// a = 1
// it's because a will take the value (which is not null) from left
var a = 0 || 2;
// so for this a=2; //its because the closest is 2 (which is not null)
var a = 0 || 2 || 1; //here also a = 2;
Your expression:
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
// _ = closest of the expression which is not null
// in your case it must be (obj.fn && obj.fn())
// so you are gettig this
Another expression:
var a = 1 && 2;
// a = 2
var a = 1 && 2 && 3;
// a = 3 //for && operator it will take the fartest value
// as long as every expression is true
var a = 0 && 2 && 3;
// a = 0
Another expression:
var _ = obj && obj._;
// _ = obj._
In most programming languages, the && and || operators returns boolean. In JavaScript it's different.
OR Operator:
It returns the value of the first operand that validates as true (if any), otherwise it returns the value of the last operand (even if it validates as false).
Example 1:
var a = 0 || 1 || 2 || 3;
^ ^ ^ ^
f t t t
^
first operand that validates as true
so, a = 1
Example 2:
var a = 0 || false || null || '';
^ ^ ^ ^
f f f f
^
no operand validates as true,
so, a = ''
AND Operator:
It returns the value of the last operand that validates as true (if all conditions validates as true), otherwise it returns the value of the first operand that validates as false.
Example 1:
var a = 1 && 2 && 3 && 4;
^ ^ ^ ^
t t t t
^
last operand that validates as true
so, a = 4
Example 2:
var a = 2 && '' && 3 && null;
^ ^ ^ ^
t f t f
^
return first operand that validates as false,
so, a = ''
Conclusion:
If you want JavaScript to act the same way how other programming languages work, use Boolean() function, like this:
var a = Boolean(1 || 2 || 3);// a = true
You should think of the short-circuit operators as conditionals rather than logical operators.
x || y roughly corresponds to:
if ( x ) { return x; } else { return y; }
and x && y roughly corresponds to:
if ( x ) { return y; } else { return x; }
Given this, the result is perfectly understandable.
From MDN documentation:
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.
And here's the table with the returned values of all logical operators.
I think you have basic JavaScript methodology question here.
Now, JavaScript is a loosely typed language. As such, the way and manner in which it treats logical operations differs from that of other standard languages like Java and C++. JavaScript uses a concept known as "type coercion" to determine the value of a logical operation and always returns the value of the first true type. For instance, take a look at the code below:
var x = mystuff || document;
// after execution of the line above, x = document
This is because mystuff is an a priori undefined entity which will always evaluate to false when tested and as such, JavaScript skips this and tests the next entity for a true value. Since the document object is known to JavaScript, it returns a true value and JavaScript returns this object.
If you wanted a boolean value returned to you, you would have to pass your logical condition statement to a function like so:
var condition1 = mystuff || document;
function returnBool(cond){
if(typeof(cond) != 'boolean'){ //the condition type will return 'object' in this case
return new Boolean(cond).valueOf();
}else{ return; }
}
// Then we test...
var condition2 = returnBool(condition1);
window.console.log(typeof(condition2)); // outputs 'boolean'
We can refer to the spec(11.11) of JS here of:
Semantics
The production LogicalANDExpression :LogicalANDExpression &&BitwiseORExpression is evaluated as follows:
Evaluate LogicalANDExpression.
2.Call GetValue(Result(1)).
3.Call ToBoolean(Result(2)).
4.If Result(3) is false, return Result(2).
5.Evaluate BitwiseORExpression.
6.Call GetValue(Result(5)).
7.Return Result(6).
see here for the spec
First, it has to be true to return, so if you are testing for truthfulness then it makes no difference
Second, it lets you do assignments along the lines of:
function bar(foo) {
foo = foo || "default value";
Compare:
var prop;
if (obj.value) {prop=obj.value;}
else prop=0;
with:
var prop=obj.value||0;
Returning a truthy expression - rather than just true or false - usually makes your code shorter and still readable. This is very common for ||, not so much for &&.