As I'm writing a javascript interpreter I need to implement some basic functions. I was playing around a bit in my Chrome console I discovered this strange behavior in js. How can I interpret what is js doing in this particular case?
Thanks
As I'm writing a javascript interpreter I need to implement some basic functions. I was playing around a bit in my Chrome console I discovered this strange behavior in js. How can I interpret what is js doing in this particular case?
Thanks
Javascript's &&
operator returns the left part if it can be converted to false
, otherwise returns the right part.
So in both cases you are getting the expression on the right (since neither 012
nor true
can be converted to false
). For the first case, true
, and for the second case, 012
.
Since 012
is octal, you are getting 10
output, which is the base-10 representation of octal 12
I can't find a better link for a source, so I'll quote this one (it's not V8 specific, but should do): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
Logical AND (&&)
expr1 && expr2
Returns
expr1
if it can be converted to false; otherwise, returnsexpr2
. Thus, when used with Boolean values, && returns true if both operands can be converted to true; otherwise, returns false.
(bold is mine)
The way I interpret the &&
and ||
operators is like this:
a && b = a ? b : a;
a || b = a ? a : b;