Why null in JavaScript is greater than -1? [duplicate] - javascript

This question already has answers here:
Why `null >= 0 && null <= 0` but not `null == 0`?
(6 answers)
Closed 2 years ago.
How should I understand these?
null>0
> false
null==0
> false
null>=0
> true

The relational operators (>= and <=), perform type coercion (ToPrimitive), with a hint type of Number, all the relational operators present have this behavior.
You can see the inner details of this process in the The Abstract Relational Comparison Algorithm.
On the other hand, the Equals operator (==), if an operand is null it only returns true if the other is either null or undefined, no numeric type coercion is made.
null == undefined; // true
null == null; // true
Check the inner details of this process in the The Abstract Relational Comparison Algorithm.
Recommended articles:
typeof, == and ===
Notes on ECMAScript Equality Operators

The relative comparison operators imply a numeric context, so in those cases (>, >=) the null is converted to a number (zero).
In the == case, however, both values are treated as boolean values, and Javascript doesn't think that null should be equal to any other "falsy" values. It's kind-of weird. The equality algorithm for == has a bunch of special cases, and null is one of those. It's only == to itself and undefined.

When null is used in a numeric experession it evalutes to 0, that explains your > and >= cases.
== is more subtle. Informally, null is not the same as zero, so it kind of makes sense.

Interesting! It seems like Javascript needs a couple new identity operators like >== and <==. Although I am not sure that would make much sense, given the numerical implications of > and <.
This gives the expected result...
(null > 0 || null === 0);

Related

jQuery/Javascript the comparison operators "===" and "=="

in dreamweaver cc 2015, when i am using the comparison operators in jquery/javascript programming like:
if(x == "")
DW shows an error that Expected === and instead saw ==. My question is that what is the difference between === and == ?.
As i know in other languages like C# etc the === operator means that the comparison will check the Data Type of the value as well as the value. In javascript or jquery is there any problem if i use the == instead of === ? or still the result will be the same in jquery / javascript?
In Javascript, === do not try to coerce the type of the variables you are testing, while == will do its best to 'typecast' those variables if needed to compare them.
For instance 1 == '1' returns true, while 1 === '1' returns false since you are comparing a number to a string.
Lastly, jQuery and pure javascript both uses the same === and == operators. Hence, there will not be any difference between the two.
The MDN documentation is pretty good too.
The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. Both are equally quick.
For more you can check this answer in stack oveflow
Which equals operator (== vs ===) should be used in JavaScript comparisons?
There is a slight difference between == and === operators. If you are using == that means you are comparing just values for example (5=='5') will return you true whereas first operand is integer and the second operand is string.Now considering the same example with === i.e (5==='5') will return you false because the '===' operator will check the value as well as type conversion and in this case integer cannot be equal to the string. Hope this helps you.

Why does this set of logical operators work correctly?

So I'm doing a puzzle to evaluate Kaprekar's Routine and in the first section I need to check to make sure the 4 digit input has at least two unique digits so I did this:
let numArr = num.toString().split("");
if (numArr[0] == numArr[1] && numArr[2] && numArr[3]) {
return 0;
}
I tried searching but I keep finding links to short-circuiting operators. I was expecting to write out numArr[0] == into every && block but to my surprise it worked. Can anyone explain why this returns 0 for 3333 but does not for 1234? I assumed numArr[2] and numArr[3] would just evaluate to true automatically.
There is a thing called operator precedence. The operator with higher precedence happens first. == happens before &&. When you have more than one operator of the same precedence it goes by 'associativity' which is generally left to right (= for example is right to left); so let's take another look at your code
if ( ((numArr[0] == numArr[1]) && numArr[2]) && numArr[3] )
Let's take just the first piece. Doing 3 == 3 is true and since none of the operators are 0, the if statement is true. But with 1234, 1 == 2 is false, so the expression short circuits to false. Generally when something (like an if statement) accepts a boolean value && a non zero/undefined/false value, the expression is considered true (I may be wrong). If you do the below you should get true
if ( numArr[0] && numArr[1] && numArr[2] && numArr[3] )
To answer your other question, generally when people work with a set of data in JS they use lodash. You can find the if there is 2 unique values easily with the line blow. uniq(array, func) returns an array with unique values in the same order. See the documentation
_.uniq("3333".toString().split(""), v=>v).length >= 2 //false
_.uniq("1224".toString().split(""), v=>v).length >= 2 //true
It is because
For String 3333
num[0] is 3,num[1]=3,num[2]=3,num[3]=3
Expressions evaluate based on precedence of operators
and when the operators have the same precedence they get executed from left to right
In this case == has highest precedence over &&
so,
num[0]==num[1] ,it is 3==3 true
then
true && num[2] && num[3] => true&&3&&3 => true
For string 1234
num[0]=1,num[1]=2,num[2]=3,num[3]=4
num[0]==num[1] ,1==2 is false
so now the expression is
false && num[2] && num[3]
For && operator if the first operand is false,it ignore the rest of the expression
so now it just results as false
Hope this helps
You have three expressions being evaluated
// loose-equality, so true if after type-coersion, the values are equivalent
// this is the only condition that is actually changing in your code, unless
// you have a number with less than 4 digits
numArr[0] == numArr[1]
// is a non-empty string so it's 'truthy'
numArr[2]
// is a non-empty string so it's 'truthy'
numArr[3]
Anything that is not Falsy (false, 0, "", null, undefined, and NaN) is Truthy
Therefore, you need to write additional code to check for unique digits.

Why 0 and null are true and false with equal operator? [duplicate]

This question already has answers here:
Why `null >= 0 && null <= 0` but not `null == 0`?
(6 answers)
JavaScript comparison operators: Identity vs. Equality
(4 answers)
Closed 6 years ago.
I want to ask about a weird javascript thing. All of these conditions, in my opinion, contradict each other and return false:
0 > null
0 < null
0 == null
0 === null
Why does using >= and <= operators return true? >= means gt and <= means lt. They couldn’t be equals. Moreover, “null” has a null value, 0 has a null value and, for the logic 0 > null should return true. Could someone explain me this fact?
When you use > and <, null is converted to the number 0. 0 > 0 and 0 < 0 are both false (that's basic math). When you use == and ===, null is not converted. 0 is not equal to null and hence both are false as well.
More generally speaking: Operators are defined for specific data types and if you pass a value of a different data type that value will be converted to the expected data type first. > and < are defined for strings and numbers but not for null. Hence null is (eventually) converted to a number.
== are a little different ===. While == usually performs type conversion, it doesn't do that if you compare against null. That's simply how the algorithm works.

null and undefined inconsistent comparison

I'm curious to know why
null == undefined
returns true but
null >= undefined
returns false
Is the inclusion of the greater than operator coercing the values differently?
tl;dr The >= ends up coercing both arguments to numbers in this case: undefined gets coerced to NaN while null gets coerced to 0, which aren't equal. For ==, the spec explicitly defines that null == undefined is true.
The values do, in fact, get coerced in both cases (in a sense, at least - the case with == is special). Let's consider them one at a time, with the help of the spec.
The algorithm for the >= operator uses the "Abstract Relational Comparison Algorithm", which is shared by other relational operators. From the description in the spec, we see that the algorithm does the following:
Converts the arguments to primitives (which null and undefined already are).
Checks if the arguments are Strings (which they are not).
If they are not Strings, the algorithm converts the arguments to numbers (see steps 3.a. and 3.b.) and performs the comparison with the results.
The last point is the key. From the ToNumber table, we see that undefined gets coerced to NaN, and the algorithm considers any comparison with NaN as being falsy (see steps 3.c. and 3.d.). Thus, null >= undefined is false.
For the other case, ==, the story is actually much simpler: the spec explicitly states that null == undefined is true as part of the "Abstract Equality Comparison Algorithm" (see steps 2. and 3.). Thus, null == undefined is true.
In JS == operator coerces values to same type to compare, so 1=="1" is true. Use === operator for exact type matching

javascript comparison crises

I came across the following and was unable to grasp the reason, can anyone explain please?
var foo = [0];
console.log(foo == !foo); // true
console.log(foo == foo); // true
The second comparison is simple to explain: foo is equal to itself.
The first one, however, is a bit tricky: foo is an array, which is an object, which evaluates to true when coerced to boolean. So !foo is false. But foo on the left side of the comparison is not being converted to boolean. Both operands are actually converted to numbers during the equality comparison. This is how it evaluates:
[0] == false
[0] == 0
"0" == 0
0 == 0
true
According to MDN, on comparisons with the equality operator ==:
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible
I know this explanation sounds superficial. It's actually much more complicated than that, but the basic steps are the ones I listed above. You can see the details on the ECMA-262 specification, particularly on sections 9 and 11.9.
You should use "===" and "!==" instead of "==" and "!="
More explanations there:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
http://net.tutsplus.com/tutorials/javascript-ajax/the-10-javascript-mistakes-youre-making/

Categories