Javascript && operator behavior in chrome's V8 [duplicate] - javascript

This question already has answers here:
Javascript AND operator within assignment
(7 answers)
Closed 6 years ago.
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, returns expr2. 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;

Related

How to deal with logical operator in javascript [duplicate]

This question already has answers here:
How does the bitwise complement operator (~ tilde) work?
(18 answers)
Closed 2 years ago.
When I deal with logical operator,I came up some questions.
I tried my work like below code.
a:true
b:false
then
(a|b):true (1)
but
~(a|b):-2
why this operator returns -2? and what is -2?
I guess this operator means not (a|b)therefore I expected to return 0
If someone has opinion,please let me know.
Thanks
let a = (4>1)
let b = (3<1)
console.log("a:",a);
console.log("b:",b);
console.log("(a|b):",(a|b));
console.log("~(a|b):",~(a|b));
if((a|b)){
console.log("#")
}
if(~(a|b)){
console.log("#2")
}
Its a bit verbose because its maybe over commented but heres my answer in summary.
Theres two issues here.
The second one is simple. Javascript uses the exclamation mark to express NOT. "!true==false" whereas "~true==WTF?"
The first one took me a little to get my head round when I learned it. Theres two different OR operators.
A single "|" is used for bitwise oprations like
5 | 4 = 5 (because 5 is composed 1 + 4)
6 | 1 = 7 (becasue 6 is composed 2 + 4 and the 1 makes 1+2+4=7)
The double "||" is used for logical operations such that every value operated on is
regarded as a boolean.
true || 0 = true
true || 12345 = true
123 || 456 = true
0 || null = false
The & also has its equivalent && to distinguish between bitwise and logical operations.
In short the "|","&" operators always return integer values and the "||","&&" always return boolean values.
Your code adjusted verbosely:
let a = (4>1); //resolves to boolean true (4 is greater than 1)
let b = (3<1); //resolves to boolean false (3 is not less than 1)
console.log("a:",a); //(logs a boolean value of a (true)
console.log("b:",b); //(logs a boolean value of b (false)
//"bitwise OR" operation on the integer values (a=0x0001,b=0x0000)
//which just luckily resolved to 0x0001 which resolves to true in boolean context
console.log("(a|b):",(a|b));
//"logical OR" operation on the boolean values (a=true,b=false)
console.log("(a||b):",(a||b));
//incorrect NOT operator for javascript "~"
console.log("~(a|b):",~(a|b));
//correct NOT operator for javascript "!" using "bitwise OR" on integers
console.log("!(a|b):",!(a|b));
//correct NOT operator for javascript "!" using "logical OR" on booleans
console.log("!(a||b):",!(a||b));
if((a|b)){
console.log("#")
}
if(~(a|b)){
console.log("#2")
}

In Javascript console.log( (NaN||9) ); // returns 9 , why is this so? [duplicate]

This question already has answers here:
JavaScript OR (||) variable assignment explanation
(12 answers)
Closed 5 years ago.
I've noticed when I have:
console.log(( NaN||9) ); // returns 9
Why is this so?
Why, when you evaluate - put parentheses around - NaN OR 9, it chooses the 9?
It works with 0, -3, "f". Can someone please tell me what is going on in the background to cause this outcome??
In JavaScript, NaN is a "falsy" value. The || operator evaluates to either its first argument (if that is "truthy") or else to the second argument (if the first argument is "falsy"). Hence NaN || 9 evaluates to 9.
From the docs for logical operators:
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 may return a non-Boolean value.
and for || specifically:
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.
Short answer, because NaN is falsy.
Here's a list of falsy values in javascript.
The logical OR opertator || in javascript can be tricky, but once you know how it works its both straightforward and very handy. If it's left side is falsy, then it's result will be whatever it's right side is (in your case, the number 9).

Javascript operator ||0? [duplicate]

This question already has answers here:
JavaScript OR (||) variable assignment explanation
(12 answers)
Closed 5 years ago.
I'm trying to translate a Javascript function to C# when I encountered something I've never seen before:
return (a / (b - (c * G * (d || 0)))) || 0;
C# is complaining about the d || 0 portion being applied to floating point number, and I have no idea what that Javascript operator does. (in C#, it's a logical OR)
Edit: all variables are floating point numbers.
The || operator returns the expression on the left side if that expression is truthy, otherwise it returns the expression on the right side. It's commonly used like this to specify default/fallback values, for instance, when a number is expected but the provided variable might contain undefined or null. It's also commonly used when optional arguments can be passed to a function and the function want's to simply use the first one that's truthy.
|| is the "short-circuited" OR operator and in order for it to work, both operands must first be evaluated as Booleans. From left to right, the value of the first expression that can be converted to true is returned (the original value, not the converted Boolean).
JavaScript will perform an implicit conversion to determine the "truthiness" of each operand if necessary, but C# will not. A float in C# is invalid with this operator because C# is a strongly-typed language and implicit conversions do not occur. You would have to explicitly cast your float to a Boolean to be able to use this operator in C#.
In C#, you'd need:
((bool) d || 0)
|| (OR)operator works when both the operands are Boolean. If not then JavaScript tries to implicitly convert it and perform the OR operation.
You need to explicitly cast in C#.

what's the " !~" mean in javascript [duplicate]

This question already has answers here:
What does a tilde do when it precedes an expression?
(5 answers)
Closed 8 years ago.
(function () {
var names = [];
return function (name) {
addName(name);
}
function addName(name) {
if (!~names.indexOf(name))//
names.push(name);
console.log(names);// ["linkFly"]
}
}())('linkFly');
sometimes i have seen this logical,what is it mean ?
thanks ~
tl;dr
indexOf returns -1 when an element cannot be found in an array. Therefore, the if statement is checking if name could not be found in names. !~-1 ==> true
Longer version:
The tilde (~) operator (bitwise NOT) yields the inverted value (a.k.a. one’s complement) of a. [Source] For example, ~-1 === 0. Note that 0 == false and !0 === true. indexOf returns -1 when an element cannot be found in an array. Therefore, we can use !~-1 === true to find out if indexOf could not find name in names (i.e. returned -1).
My opinion:
As you can see, using these obfuscated or "clever" techniques without comments can really confuse the reader. If you do love these techniques, please document what your line(s) of code are doing for the sake of the readers!
! (Logical NOT)
Returns false if its single operand can be converted to true; otherwise, returns true.
For all integer operands except -1, the net operand after applying the ~ operator for the ! operator would be truthy in nature resulting in FALSE.
-1 is special because ~(-1) gives 0 which is falsy in JavaScript. Adding the ! operator gives us the only TRUE.

Why is Javascript giving result as Number instead of True/False for expression? [duplicate]

This question already has answers here:
Why the result of bool(true) && string is string in javascript?
(4 answers)
Closed 8 years ago.
I was rambling with JavaScript code in my application today when I observed something strange.
var someVar = 25;
var anotherVar = 50;
var out = (anotherVar == 50 && someVar);
console.log(out) // outputs 25 and not true or false;
Any idea what's happening?
As stated on MDN's Logical Operators page, the && operator:
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.
In your case, expr1 (anotherVar == 50) is true (not false), so it returns expr2 (someVar), which is 25.
It doesn't return true or false because expr2 isn't a Boolean value.
The ECMA-262 Specification notes:
The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.

Categories

Resources