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

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.

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")
}

What does '!!~' do in Javascript? [duplicate]

This question already has answers here:
How does !!~ (not not tilde/bang bang tilde) alter the result of a 'contains/included' Array method call?
(13 answers)
Closed 4 years ago.
I saw following piece of code on github.
/**
* Filters an array of objects with multiple criteria.
*
* #param {Array} array: the array to filter
* #param {Object} filters: an object with the filter criteria as the property names
* #return {Array}
*/
function multiFilter(array, filters) {
const filterKeys = Object.keys(filters);
// filters all elements passing the criteria
return array.filter((item) => {
// dynamically validate all filter criteria
return filterKeys.every(key => !!~filters[key].indexOf(item[key]));
});
}
I don't understand, what does !!~ do here?
PS: I know C and C++ languages and but I'm newbie with Javascript. I know about that operators but I don't understand, Why does use double negation(!!) with bitwise not(~) operator?
indexOf will return the index 0-x if the element is found, -1 otherwise.
~ will change all the bits in the number, turning -1 to 0 (the binary represantation of -1 is 1111 1111 ...).
0 is a falsy value, all other numbers are truthy.
!! will convert a falsy value to false and a truthy value to true. It wouldn't be needed here, because every doesn't care whether it recieves a truthy value or true.
As others have mentioned, nowadays you could use includes. However, includes is newer to the JavaScript ecosystem than indexOf, so this solution would work in IE, the solution with include would not. You could still use includes in IE either by providing a polyfill or by transpiling your code.
The tilde turns the resulting indexOf expression truthy if the item is found, and falsey if the item is not found. The !! then converts the result to a boolean from a number. (which is not useful at all, since every only cares about whether the result is truthy or falsey)
It's terribly unclear. It would be much better to use this instead:
return array.filter((item) => {
// dynamically validate all filter criteria
return filterKeys.every(key => filters[key].includes(item[key]));
});
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = ~fruits.indexOf("Banana");
var b = !a;
var c = !!a;
console.log('a:',a);
console.log('b:',b);
console.log('c:',c);
It can be break into steps as above to trying to understand what's going on. Bitwise operator: ~ is a common way to replace the ugly 0/-1 comparison when using indexOf method. A double negation using !! will gives us a Boolean to tell whether it's found or not found
!!~ means bitwise not ~ followed by double negation !!.
Bitwise not operates by reversing all the bits in the operand.

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 behavior in chrome's V8 [duplicate]

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;

Why does typeof 3>2 return false in javascript console? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The following link provides a description and examples about how typeof works:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
Because typeof 3 is not more than 2.
You need parentheses.
To explain what's going on, the interpreter treats it as:
(typeof 3) > 2
The typeof operator always returns a string, and 3 is a number so the expression resolves to:
'number' > 2
The Greater-than Operator ( > ) applies the Abstract Relational Comparison Algorithm to get the result of the comparison. Since 'number' is a String, it's converted to a Number using the internal ToNumber operation (step 3a). A string that doesn't contain a number literal (e.g. "3") results in NaN (see note below), so now the expression is:
NaN > 2
Step 3c says if the left hand expression is NaN, return undefined (that is, the special undefined value, not the string 'undefined').
So undefined is returned, and step 6 of the greater–than operator algorithm says:
If [the result] is undefined, return false. Otherwise, return [the result].
so ultimately, the expression returns false.
Note: a string containing only whitespace (one or more spaces, tabs, newlines, etc.) converts to the number 0, which is the only case where a string that isn't a numeric literal converts to a number value other than NaN. See ToNumber Applied to the String Type.
In JavaScript the operator "typeof" has a precedence of 4 while the operator greater ">" than has a precedence of 8, so according to the example mentioned in the question typeof 3 gets evaluated first and then compared to 2 which returns false.
More details can be found about precedence and associativity of operators at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Categories

Resources