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")
}
Related
This question already has answers here:
What are bitwise operators?
(9 answers)
Closed 1 year ago.
The following code checks if sum has operand, the code is very straightforward, but I'm confused by the condition (sum & operand) === operand.
I've read the Bitwise AND (&) doc, confused me even more, can someone explain it in simple terms?
const has = (sum, operand) => (sum & operand) === operand
console.log(has(7, 4))
This kind of code is usually used when you are working with bitflags. Essentially you want to check if the operand bits are set in the sum aswell.
The binary representation of 7 is 00000111, while the binary representation of 4 is 00000100.
By performing the bitwise AND operation A & B you are "preserving" the identical bits between the two, while setting all other bits to 0. Comparing the result with B again yields you the insight if all bits that are set in B are also set in A.
This question already has answers here:
Why is `null + 1 = 1` but `undefined + 1 = NaN`?
(3 answers)
Closed 3 years ago.
I understand the implicit coercion that happens in javascript, but i actually can't understand why this happens:
isNaN(1 + null) // false
isNaN(1 + undefined) // true
As i know that JS convert the null & undefined to 0, Or we could say consider them false value.
what is the difference here ?
Javascript converts null to 0 but undefined is converted to NaN.
check it out using the built in fucntion Number .
So in this case (1+ null) is similar to 1+ 0 which is 1
and (1+ undefined) is similar 1 + NaN which is NaN.
That's why it returns true.
console.log(Number(null));
console.log(Number(undefined));
The weird behavior here though is that Javascript consider both of these types "false" when dealing with comparison operator or as a condition in if statement and false value considered 0 after implicitly coerced...
Conclusion: Js coerce undefined & null depending on the situation. if it's in condition, it try to convert it to boolean false & if it's in an arithmetic operation it try to convert it to numbers, in this case there would be difference between them:
undefined ==> NaN
null ==> 0
This question already has answers here:
What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?
(5 answers)
Closed 4 years ago.
I have came across this comparisons:
[] + [] === ''; // true
[] * 1 === 0; // true
false + 1 === 1; // true
The last comparison makes sense, but what I am wondering is and can't find a resource about why [] + [] equals empty string and why [] * 1 equals 0?
The answer linked from the comment posted by hardik-shah would certainly give you a better understanding of how these type of evaluations get handled in javascript. That answer points to the ecma docs, which is also useful. I'll try and give a limited explanation of how the examples you posted work.
Below I've quoted the article I used as the basis to interpreting how these instances of the + operator work. I believe I've interpreted the article correctly, but I'm no expert on these things so I would be happy to be corrected.
[] + [] === ''; // true
This is true because both operands are objects; [].valueOf doesn't return a primitive, so [].toString is used, which evaluates to ''
[] * 1 === 0; // true
This is true because, as one of the operands is a primitive, arithmetic is used rather than concatenation. '' * 1 evaluates to 0 * 1, which equals 0
false + 1 === 1; // true
Both operands here are primitives, so arithmetic will be used. Number(false) gives us 0, so 0 + 1 equals 1
From this article
If at least one operand is an object, it is converted to a primitive value (string, number or boolean)
After conversion, if at least one operand is string type, the second operand is converted to string and the concatenation is executed
In other case both operands are converted to numbers and arithmetic addition is executed.
The object to primitive conversion:
If object type is Date, then toString() method is used;
In other case
valueOf() method is used, if it returns a primitive value;
In other case (if valueOf() doesn't exist or doesn't return a primitive value),
then toString() method is used. This happens most of the times.
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).
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.