Why `Number(new Boolean(false)) === 0` - javascript

Boolean(new Boolean(...)) === true because new Boolean(...) is an object.
But why Number(new Boolean(false)) === 0 (+new Boolean(false) === 0) and Number(new Boolean(true)) === 1? Why not NaN*?
Why in the first example there is no unboxing, but in the second case there is it?
*isNaN(Number({})) === true

As #ASDFGerte mentioned. This is because the ToNumber() method which is called by the Number() constructor will call .ToPrimitive() on the argument if an object is passed. This is why it's treated as a Boolean primitive rather than an object.

isNaN(Number({})) === true
While this is correct, I think you're equating an object with a Boolean object and the two are not equivalent.
Let's start from the most important thing - Number converts the argument its given into a numeric. However, it doesn't arbitrarily do that - there are rules about numeric conversion and when it comes to objects, it's not as simple as "all objects are NaN". Consider this:
const obj0 = {}
const obj1 = {
toString() {
return 1;
}
}
const obj2 = {
toString() {
return 1;
},
valueOf() {
return 2;
}
}
const obj3 = {
toString() {
return 1;
},
valueOf() {
return 2;
},
[Symbol.toPrimitive]() {
return 3;
}
}
const obj4 = Object.create(null);
console.log(Number(obj0)); //NaN
console.log(Number(obj1)); //1
console.log(Number(obj2)); //2
console.log(Number(obj3)); //3
console.log(Number(obj4)); //Error
Not all objects are equal when converting to a number. Some happen to be even more unequal than others.
When Number is given an object, it goes through the process to convert it to a primitive with a preference (hint) for a number. To do this, it will go through the following steps:
Determine the hint to be "number".
Check if the object implements the ##toPrimitive method.
if so, it will call it with the hint ("number")
If that doesn't exist it will then look for a valueOf method.
this is done because the hint is "number", so valueOf will be checked first.
If that doesn't exist, then it will check for a toString method
again, this is based on the hint being "number". If the hint was "string", the last two steps would be reversed.
If that doesn't exist, then raise an error.
Once an appropriate method has been found, it's executed and the value returned will be transformed into numeric.
We haven't touched Boolean yet - this is just how the generic Number does the conversion. So, in summary - an object can be converted to a primitive number, if it implements the correct functionality to do so.
Boolean objects do implement the correct functionality - they have a valueOf method that returns the primitive boolean they hold:
const T1 = new Boolean(true);
const T2 = new Boolean(true);
console.log("T1.valueOf()", T1.valueOf());
console.log("typeof T1.valueOf()", typeof T1.valueOf());
console.log("T1 === T2", T1 === T2);
console.log("T1.valueOf() === T2.valueOf()", T1.valueOf() === T2.valueOf());
So, in that case:
Number(new Boolean(true)) = Number(new Boolean(true).valueOf()) = Number(true)
And if we generalise it a bit, then: Number(new Boolean(bool)) = Number(bool)
From the ToNumber conversion we know that true is turned into 1 while false is turned into 0. Thus the equality Number(new Boolean(false)) === 0 makes perfect sense, since Number(false) is indeed 0. Same with Number(new Boolean(true)) === 1.

Boolean objects have a valueOf method, and it can be used to customize the primitive value of the object in type conversions.
Boolean#valueOf() returns true for new Boolean(true) and false for new Boolean(false).
This method is internally called by both the Number function and the unary plus (+) operator, so the code becomes to:
Number(true)
which is equal to 1, as true has the numeric value of 1.
You can also implement a valueOf function on any object, to make it have a custom value, for example:
const object={
valueOf(){
return 10
}
}
console.log(Number(object)) //10

Because true represents 1
and false represents 0
0 is false because they’re both zero elements in common
[semirings][Semiring on Wikipedia]. Even though they are distinct data
types, it makes intuitive sense to convert between them because they
belong to isomorphic algebraic structures.
0 is the identity for addition and zero for multiplication. This is true for integers and rationals, but not IEEE-754 floating-point
numbers: 0.0 * NaN = NaN and 0.0 * Infinity = NaN.
false is the identity for Boolean xor (⊻) and zero for Boolean and (∧). If Booleans are represented as {0, 1}—the set of integers modulo 2—you can think of ⊻ as addition without carry and ∧ as
multiplication.
"" and [] are identity for concatenation, but there are several operations for which they make sense as zero. Repetition is one, but
repetition and concatenation do not distribute, so these operations
don’t form a semiring.
Such implicit conversions are helpful in small programs, but in the
large can make programs more difficult to reason about. Just one of
the many tradeoffs in language design.
[Semiring on Wikipedia]: http://en.wikipedia.org/wiki/Semiring
quote from
read this
1 = false and 0 = true?

Related

Execute query in portions and return values jQuery php [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace == (two equals signs) with === (three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement.
Is there a performance benefit to replacing == with ===?
Any performance improvement would be welcomed as many comparison operators exist.
If no type conversion takes place, would there be a performance gain over ==?
The strict equality operator (===) behaves identically to the abstract equality operator (==) except no type conversion is done, and the types must be the same to be considered equal.
Reference: Javascript Tutorial: Comparison Operators
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.
To quote Douglas Crockford's excellent JavaScript: The Good Parts,
JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true
The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.
Update:
A good point was brought up by #Casebash in the comments and in #Phillipe Laybaert's answer concerning objects. For objects, == and === act consistently with one another (except in a special case).
var a = [1,2,3];
var b = [1,2,3];
var c = { x: 1, y: 2 };
var d = { x: 1, y: 2 };
var e = "text";
var f = "te" + "xt";
a == b // false
a === b // false
c == d // false
c === d // false
e == f // true
e === f // true
The special case is when you compare a primitive with an object that evaluates to the same primitive, due to its toString or valueOf method. For example, consider the comparison of a string primitive with a string object created using the String constructor.
"abc" == new String("abc") // true
"abc" === new String("abc") // false
Here the == operator is checking the values of the two objects and returning true, but the === is seeing that they're not the same type and returning false. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the String constructor to create string objects from string literals.
Reference
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
Using the == operator (Equality)
true == 1; //true, because 'true' is converted to 1 and then compared
"2" == 2; //true, because "2" is converted to 2 and then compared
Using the === operator (Identity)
true === 1; //false
"2" === 2; //false
This is because the equality operator == does type coercion, meaning that the interpreter implicitly tries to convert the values before comparing.
On the other hand, the identity operator === does not do type coercion, and thus does not convert the values when comparing.
Here's an interesting visualisation of the equality comparison between == and ===.
Source: https://github.com/dorey/JavaScript-Equality-Table (demo, unified demo)
var1 === var2
When using === for JavaScript equality testing, everything is as is.
Nothing gets converted before being evaluated.
var1 == var2
When using == for JavaScript equality testing, some funky conversions take place.
Summary of equality in Javascript
Conclusion:
Always use ===, unless you fully understand the funky conversions that take place with ==.
In the answers here, I didn't read anything about what equal means. Some will say that === means equal and of the same type, but that's not really true. It actually means that both operands reference the same object, or in case of value types, have the same value.
So, let's take the following code:
var a = [1,2,3];
var b = [1,2,3];
var c = a;
var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true
The same here:
var a = { x: 1, y: 2 };
var b = { x: 1, y: 2 };
var c = a;
var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true
Or even:
var a = { };
var b = { };
var c = a;
var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true
This behavior is not always obvious. There's more to the story than being equal and being of the same type.
The rule is:
For value types (numbers):
a === b returns true if a and b have the same value and are of the same type
For reference types:
a === b returns true if a and b reference the exact same object
For strings:
a === b returns true if a and b are both strings and contain the exact same characters
Strings: the special case...
Strings are not value types, but in Javascript they behave like value types, so they will be "equal" when the characters in the string are the same and when they are of the same length (as explained in the third rule)
Now it becomes interesting:
var a = "12" + "3";
var b = "123";
alert(a === b); // returns true, because strings behave like value types
But how about this?:
var a = new String("123");
var b = "123";
alert(a === b); // returns false !! (but they are equal and of the same type)
I thought strings behave like value types? Well, it depends who you ask... In this case a and b are not the same type. a is of type Object, while b is of type string. Just remember that creating a string object using the String constructor creates something of type Object that behaves as a string most of the time.
Let me add this counsel:
If in doubt, read the specification!
ECMA-262 is the specification for a scripting language of which JavaScript is a dialect. Of course in practice it matters more how the most important browsers behave than an esoteric definition of how something is supposed to be handled. But it is helpful to understand why new String("a") !== "a".
Please let me explain how to read the specification to clarify this question. I see that in this very old topic nobody had an answer for the very strange effect. So, if you can read a specification, this will help you in your profession tremendously. It is an acquired skill. So, let's continue.
Searching the PDF file for === brings me to page 56 of the specification: 11.9.4. The Strict Equals Operator ( === ), and after wading through the specificationalese I find:
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
  1. If Type(x) is different from Type(y), return false.
  2. If Type(x) is Undefined, return true.
  3. If Type(x) is Null, return true.
  4. If Type(x) is not Number, go to step 11.
  5. If x is NaN, return false.
  6. If y is NaN, return false.
  7. If x is the same number value as y, return true.
  8. If x is +0 and y is −0, return true.
  9. If x is −0 and y is +0, return true.
  10. Return false.
  11. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
  12. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
  13. Return true if x and y refer to the same object or if they refer to objects joined to each other (see 13.1.2). Otherwise, return false.
Interesting is step 11. Yes, strings are treated as value types. But this does not explain why new String("a") !== "a". Do we have a browser not conforming to ECMA-262?
Not so fast!
Let's check the types of the operands. Try it out for yourself by wrapping them in typeof(). I find that new String("a") is an object, and step 1 is used: return false if the types are different.
If you wonder why new String("a") does not return a string, how about some exercise reading a specification? Have fun!
Aidiakapi wrote this in a comment below:
From the specification
11.2.2 The new Operator:
If Type(constructor) is not Object, throw a TypeError exception.
With other words, if String wouldn't be of type Object it couldn't be used with the new operator.
new always returns an Object, even for String constructors, too. And alas! The value semantics for strings (see step 11) is lost.
And this finally means: new String("a") !== "a".
I tested this in Firefox with Firebug using code like this:
console.time("testEquality");
var n = 0;
while (true) {
n++;
if (n == 100000)
break;
}
console.timeEnd("testEquality");
and
console.time("testTypeEquality");
var n = 0;
while (true) {
n++;
if (n === 100000)
break;
}
console.timeEnd("testTypeEquality");
My results (tested five times each and averaged):
==: 115.2
===: 114.4
So I'd say that the miniscule difference (this is over 100000 iterations, remember) is negligible. Performance isn't a reason to do ===. Type safety (well, as safe as you're going to get in JavaScript), and code quality is.
In PHP and JavaScript, it is a strict equality operator. Which means, it will compare both type and values.
In JavaScript it means of the same value and type.
For example,
4 == "4" // will return true
but
4 === "4" // will return false
Why == is so unpredictable?
What do you get when you compare an empty string "" with the number zero 0?
true
Yep, that's right according to == an empty string and the number zero are the same time.
And it doesn't end there, here's another one:
'0' == false // true
Things get really weird with arrays.
[1] == true // true
[] == false // true
[[]] == false // true
[0] == false // true
Then weirder with strings
[1,2,3] == '1,2,3' // true - REALLY?!
'\r\n\t' == 0 // true - Come on!
It get's worse:
When is equal not equal?
let A = '' // empty string
let B = 0 // zero
let C = '0' // zero string
A == B // true - ok...
B == C // true - so far so good...
A == C // **FALSE** - Plot twist!
Let me say that again:
(A == B) && (B == C) // true
(A == C) // **FALSE**
And this is just the crazy stuff you get with primitives.
It's a whole new level of crazy when you use == with objects.
At this point your probably wondering...
Why does this happen?
Well it's because unlike "triple equals" (===) which just checks if two values are the same.
== does a whole bunch of other stuff.
It has special handling for functions, special handling for nulls, undefined, strings, you name it.
It get's pretty wacky.
In fact, if you tried to write a function that does what == does it would look something like this:
function isEqual(x, y) { // if `==` were a function
if(typeof y === typeof x) return y === x;
// treat null and undefined the same
var xIsNothing = (y === undefined) || (y === null);
var yIsNothing = (x === undefined) || (x === null);
if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);
if(typeof y === "function" || typeof x === "function") {
// if either value is a string
// convert the function into a string and compare
if(typeof x === "string") {
return x === y.toString();
} else if(typeof y === "string") {
return x.toString() === y;
}
return false;
}
if(typeof x === "object") x = toPrimitive(x);
if(typeof y === "object") y = toPrimitive(y);
if(typeof y === typeof x) return y === x;
// convert x and y into numbers if they are not already use the "+" trick
if(typeof x !== "number") x = +x;
if(typeof y !== "number") y = +y;
// actually the real `==` is even more complicated than this, especially in ES6
return x === y;
}
function toPrimitive(obj) {
var value = obj.valueOf();
if(obj !== value) return value;
return obj.toString();
}
So what does this mean?
It means == is complicated.
Because it's complicated it's hard to know what's going to happen when you use it.
Which means you could end up with bugs.
So the moral of the story is...
Make your life less complicated.
Use === instead of ==.
The End.
The === operator is called a strict comparison operator, it does differ from the == operator.
Lets take 2 vars a and b.
For "a == b" to evaluate to true a and b need to be the same value.
In the case of "a === b" a and b must be the same value and also the same type for it to evaluate to true.
Take the following example
var a = 1;
var b = "1";
if (a == b) //evaluates to true as a and b are both 1
{
alert("a == b");
}
if (a === b) //evaluates to false as a is not the same type as b
{
alert("a === b");
}
In summary; using the == operator might evaluate to true in situations where you do not want it to so using the === operator would be safer.
In the 90% usage scenario it won't matter which one you use, but it is handy to know the difference when you get some unexpected behaviour one day.
=== checks same sides are equal in type as well as value.
Example:
'1' === 1 // will return "false" because `string` is not a `number`
Common example:
0 == '' // will be "true", but it's very common to want this check to be "false"
Another common example:
null == undefined // returns "true", but in most cases a distinction is necessary
Many times an untyped check would be handy because you do not care if the value is either undefined, null, 0 or ""
Javascript execution flow diagram for strict equality / Comparison '==='
Javascript execution flow diagram for non strict equality / comparison '=='
JavaScript === vs == .
0==false // true
0===false // false, because they are of a different type
1=="1" // true, auto type coercion
1==="1" // false, because they are of a different type
It means equality without type coercion
type coercion means JavaScript do not automatically convert any other data types to string data types
0==false // true,although they are different types
0===false // false,as they are different types
2=='2' //true,different types,one is string and another is integer but
javaScript convert 2 to string by using == operator
2==='2' //false because by using === operator ,javaScript do not convert
integer to string
2===2 //true because both have same value and same types
In a typical script there will be no performance difference. More important may be the fact that thousand "===" is 1 KB heavier than thousand "==" :) JavaScript profilers can tell you if there is a performance difference in your case.
But personally I would do what JSLint suggests. This recommendation is there not because of performance issues, but because type coercion means ('\t\r\n' == 0) is true.
The equal comparison operator == is confusing and should be avoided.
If you HAVE TO live with it, then remember the following 3 things:
It is not transitive: (a == b) and (b == c) does not lead to (a == c)
It's mutually exclusive to its negation: (a == b) and (a != b) always hold opposite Boolean values, with all a and b.
In case of doubt, learn by heart the following truth table:
EQUAL OPERATOR TRUTH TABLE IN JAVASCRIPT
Each row in the table is a set of 3 mutually "equal" values, meaning that any 2 values among them are equal using the equal == sign*
** STRANGE: note that any two values on the first column are not equal in that sense.**
'' == 0 == false // Any two values among these 3 ones are equal with the == operator
'0' == 0 == false // Also a set of 3 equal values, note that only 0 and false are repeated
'\t' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\r' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\t\r\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
null == undefined // These two "default" values are not-equal to any of the listed values above
NaN // NaN is not equal to any thing, even to itself.
There is unlikely to be any performance difference between the two operations in your usage. There is no type-conversion to be done because both parameters are already the same type. Both operations will have a type comparison followed by a value comparison.
Simply
== means comparison between operands with type coercion
and
=== means comparison between operands without type coercion.
Type coercion in JavaScript means automatically converting data types to other data types.
For example:
123 == "123" // Returns true, because JS coerces string "123" to number 123
// and then goes on to compare `123 == 123`.
123 === "123" // Returns false, because JS does not coerce values of different types here.
Yes! It does matter.
=== operator in javascript checks value as well as type where as == operator just checks the value (does type conversion if required).
You can easily test it. Paste following code in an HTML file and open it in browser
<script>
function onPageLoad()
{
var x = "5";
var y = 5;
alert(x === 5);
};
</script>
</head>
<body onload='onPageLoad();'>
You will get 'false' in alert. Now modify the onPageLoad() method to alert(x == 5); you will get true.
As a rule of thumb, I would generally use === instead of == (and !== instead of !=).
Reasons are explained in in the answers above and also Douglas Crockford is pretty clear about it (JavaScript: The Good Parts).
However there is one single exception:
== null is an efficient way to check for 'is null or undefined':
if( value == null ){
// value is either null or undefined
}
For example jQuery 1.9.1 uses this pattern 43 times, and the JSHint syntax checker even provides the eqnull relaxing option for this reason.
From the jQuery style guide:
Strict equality checks (===) should be used in favor of ==. The only
exception is when checking for undefined and null by way of null.
// Check for both undefined and null values, for some important reason.
undefOrNull == null;
EDIT 2021-03:
Nowadays most browsers
support the Nullish coalescing operator (??)
and the Logical nullish assignment (??=), which allows a more concise way to
assign a default value if a variable is null or undefined, for example:
if (a.speed == null) {
// Set default if null or undefined
a.speed = 42;
}
can be written as any of these forms
a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;
It's a strict check test.
It's a good thing especially if you're checking between 0 and false and null.
For example, if you have:
$a = 0;
Then:
$a==0;
$a==NULL;
$a==false;
All returns true and you may not want this. Let's suppose you have a function that can return the 0th index of an array or false on failure. If you check with "==" false, you can get a confusing result.
So with the same thing as above, but a strict test:
$a = 0;
$a===0; // returns true
$a===NULL; // returns false
$a===false; // returns false
=== operator checks the values as well as the types of the variables for equality.
== operator just checks the value of the variables for equality.
JSLint sometimes gives you unrealistic reasons to modify stuff. === has exactly the same performance as == if the types are already the same.
It is faster only when the types are not the same, in which case it does not try to convert types but directly returns a false.
So, IMHO, JSLint maybe used to write new code, but useless over-optimizing should be avoided at all costs.
Meaning, there is no reason to change == to === in a check like if (a == 'test') when you know it for a fact that a can only be a String.
Modifying a lot of code that way wastes developers' and reviewers' time and achieves nothing.
A simple example is
2 == '2' -> true, values are SAME because of type conversion.
2 === '2' -> false, values are NOT SAME because of no type conversion.
The top 2 answers both mentioned == means equality and === means identity. Unfortunately, this statement is incorrect.
If both operands of == are objects, then they are compared to see if they are the same object. If both operands point to the same object, then the equal operator returns true. Otherwise,
the two are not equal.
var a = [1, 2, 3];
var b = [1, 2, 3];
console.log(a == b) // false
console.log(a === b) // false
In the code above, both == and === get false because a and b are not the same objects.
That's to say: if both operands of == are objects, == behaves same as ===, which also means identity. The essential difference of this two operators is about type conversion. == has conversion before it checks equality, but === does not.
The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...
var x = 0;
var isTrue = x == null;
var isFalse = x === null;
Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...
CString x;
delete x;
Which obviously during runtime does very undefined things...
Google for implicit conversions in C++ and STL to get some of the arguments against it...
From the core javascript reference
=== Returns true if the operands are strictly equal (see above)
with no type conversion.
Equality comparison:
Operator ==
Returns true, when both operands are equal. The operands are converted to the same type before being compared.
>>> 1 == 1
true
>>> 1 == 2
false
>>> 1 == '1'
true
Equality and type comparison:
Operator ===
Returns true if both operands are equal and of the same type. It's generally
better and safer if you compare this way, because there's no behind-the-scenes type conversions.
>>> 1 === '1'
false
>>> 1 === 1
true
Here is a handy comparison table that shows the conversions that happen and the differences between == and ===.
As the conclusion states:
"Use three equals unless you fully understand the conversions that take
place for two-equals."
http://dorey.github.io/JavaScript-Equality-Table/
null and undefined are nothingness, that is,
var a;
var b = null;
Here a and b do not have values. Whereas, 0, false and '' are all values. One thing common beween all these are that they are all falsy values, which means they all satisfy falsy conditions.
So, the 0, false and '' together form a sub-group. And on other hand, null & undefined form the second sub-group. Check the comparisons in the below image. null and undefined would equal. The other three would equal to each other. But, they all are treated as falsy conditions in JavaScript.
This is same as any object (like {}, arrays, etc.), non-empty string & Boolean true are all truthy conditions. But, they are all not equal.

Why is [0] === [0] false

If debugging shows that a variable is 0, then I think that I should be able to catch it with either ==='0' or ===0 but that didn't work. I had to use only == instead, then it worked:
var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns == '0' || non_sortable_columns == 0) {
offset = 1;
}
I first tried this but it didn't work:
var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns === '0' || non_sortable_columns === 0) {
offset = 1;
}
The value was [0] and [0] === [0] is false. How can it be false?
1. [0] === [0] is false because each [0] is actually a declaration that creates an array with the number 0 as its first index. Arrays are objects and in JavaScript, 2 objects are == or === only and only if they point at the same location in memory. This means:
var a = [];
var b = a;
console.log(a == b); // "true". They both point at the same location in memory.
a = [];
b = [];
console.log(a == b); // "false". They don't point at the same location in memory.
2. [0] == "0" evaluates to true, because: In JavaScript, due to the nature of the == operator, when you compare an object with a primitive, the object will be coerced to a primitive, and then that primitive will be coerced to the specific type of primitive you are trying to compare it with.
"0" is a string, so [0] will have to be coerced to a string. How ? First, JavaScript will invoke its valueOf method to see if it returns a primitive, the array version of valueOf will just return that array, so valueOf doesn't yield a primitive; now JavaScript will try the object's (aka array's) toString method, an array's toString method will return a string that is the result of a comma-separated concatenation of its elements (each element will be coerced to a string as well, but that is irrelevant here), this would have been more visible if your array contained more than one element (e.g if it were [0,1], toString would return "0,1"), but your array only has 1 element, so the result of its stringification is "0" (if toString didn't return a string but another primitive, that primitive would be used in a ToString abstract operation; if neither valueOf nor toString returned a primitive, a TypeError would be thrown).
Now, our end comparison, with all the coercions and stuff, has changed to "0" == "0", which is true.
3. [0] == 0, mostly the same as #2, except after JavaScript has the string "0", it will coerce it to a number, the result of coercing the string "0" to a number is the number 0. So we have 0 == 0 which is true.
4. [0] === 0 and [0] === "0", these 2 are very simple, no coercions will happen because you are using ===.
In the first one, the reference (aka location pointed at in memory) held by [0] will be compared to the number 0, this will obviously evaluate to false;
In the second one, again, the reference held by [0] will be compared with the string "0", this again, is false.
So, as you can see, good ser, all your misery comes from ==, this operator, along with !=, are called "the evil counterparts of === and !==" by Douglas Crockford, for the same reasons which are causing your confusions.
Feel free to request any elaborations you might want and ask any questions you might have.
Additionally, see this article about object coercion, this MDN article about Array#toString, and this StackOverflow question which outlines the differences between == and ===.
I just did the following test
var num = 0;
console.log("Number: ", num);
if(num === '0' || num === 0) {
console.log("Num is 0 (===)");
}
if(num == '0' || num == 0) {
console.log("Num is 0 (==)");
}
and got the output
Number: 0
Num is 0 (===)
Num is 0 (==)
Try console.log the value itself, if you alert or append strings to a number in JS it will always output as a string. This can be misleading when trying to debug code.
The value of non_sortable_columns might be false.
The basic difference between the === and == is that the 3 equals to comparison operator also checks the type of the variable, that means: '0' which is a string would not be equal to: 0 which is a number.
In your case the variable non_sortable_columns value might be false which means 0in JavaScript therefore the value of the == finds it same as it doesn't check the type but === fails as it checks the type of it.
For better understanding refer to: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Javascript == and === comparison [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace == (two equals signs) with === (three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement.
Is there a performance benefit to replacing == with ===?
Any performance improvement would be welcomed as many comparison operators exist.
If no type conversion takes place, would there be a performance gain over ==?
The strict equality operator (===) behaves identically to the abstract equality operator (==) except no type conversion is done, and the types must be the same to be considered equal.
Reference: JavaScript Tutorial: Comparison Operators
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.
To quote Douglas Crockford's excellent JavaScript: The Good Parts,
JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. The rules by which they do that are complicated and unmemorable. These are some of the interesting cases:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true
The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.
Update
A good point was brought up by #Casebash in the comments and in #Phillipe Laybaert's answer concerning objects. For objects, == and === act consistently with one another (except in a special case).
var a = [1,2,3];
var b = [1,2,3];
var c = { x: 1, y: 2 };
var d = { x: 1, y: 2 };
var e = "text";
var f = "te" + "xt";
a == b // false
a === b // false
c == d // false
c === d // false
e == f // true
e === f // true
The special case is when you compare a primitive with an object that evaluates to the same primitive, due to its toString or valueOf method. For example, consider the comparison of a string primitive with a string object created using the String constructor.
"abc" == new String("abc") // true
"abc" === new String("abc") // false
Here the == operator is checking the values of the two objects and returning true, but the === is seeing that they're not the same type and returning false. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the String constructor to create string objects from string literals.
Reference
https://262.ecma-international.org/5.1/#sec-11.9.3
Using the == operator (Equality)
true == 1; //true, because 'true' is converted to 1 and then compared
"2" == 2; //true, because "2" is converted to 2 and then compared
Using the === operator (Identity)
true === 1; //false
"2" === 2; //false
This is because the equality operator == does type coercion, meaning that the interpreter implicitly tries to convert the values before comparing.
On the other hand, the identity operator === does not do type coercion, and thus does not convert the values when comparing.
Here's an interesting visualisation of the equality comparison between == and ===.
Source: https://github.com/dorey/JavaScript-Equality-Table (demo, unified demo)
var1 === var2
When using === for JavaScript equality testing, everything is as is.
Nothing gets converted before being evaluated.
var1 == var2
When using == for JavaScript equality testing, some funky conversions take place.
Summary of equality in Javascript
Conclusion:
Always use ===, unless you fully understand the funky conversions that take place with ==.
In the answers here, I didn't read anything about what equal means. Some will say that === means equal and of the same type, but that's not really true. It actually means that both operands reference the same object, or in case of value types, have the same value.
So, let's take the following code:
var a = [1,2,3];
var b = [1,2,3];
var c = a;
var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true
The same here:
var a = { x: 1, y: 2 };
var b = { x: 1, y: 2 };
var c = a;
var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true
Or even:
var a = { };
var b = { };
var c = a;
var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true
This behavior is not always obvious. There's more to the story than being equal and being of the same type.
The rule is:
For value types (numbers):
a === b returns true if a and b have the same value and are of the same type
For reference types:
a === b returns true if a and b reference the exact same object
For strings:
a === b returns true if a and b are both strings and contain the exact same characters
Strings: the special case...
Strings are not value types, but in Javascript they behave like value types, so they will be "equal" when the characters in the string are the same and when they are of the same length (as explained in the third rule)
Now it becomes interesting:
var a = "12" + "3";
var b = "123";
alert(a === b); // returns true, because strings behave like value types
But how about this?:
var a = new String("123");
var b = "123";
alert(a === b); // returns false !! (but they are equal and of the same type)
I thought strings behave like value types? Well, it depends who you ask... In this case a and b are not the same type. a is of type Object, while b is of type string. Just remember that creating a string object using the String constructor creates something of type Object that behaves as a string most of the time.
Let me add this counsel:
If in doubt, read the specification!
ECMA-262 is the specification for a scripting language of which JavaScript is a dialect. Of course in practice it matters more how the most important browsers behave than an esoteric definition of how something is supposed to be handled. But it is helpful to understand why new String("a") !== "a".
Please let me explain how to read the specification to clarify this question. I see that in this very old topic nobody had an answer for the very strange effect. So, if you can read a specification, this will help you in your profession tremendously. It is an acquired skill. So, let's continue.
Searching the PDF file for === brings me to page 56 of the specification: 11.9.4. The Strict Equals Operator ( === ), and after wading through the specificationalese I find:
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
  1. If Type(x) is different from Type(y), return false.
  2. If Type(x) is Undefined, return true.
  3. If Type(x) is Null, return true.
  4. If Type(x) is not Number, go to step 11.
  5. If x is NaN, return false.
  6. If y is NaN, return false.
  7. If x is the same number value as y, return true.
  8. If x is +0 and y is −0, return true.
  9. If x is −0 and y is +0, return true.
  10. Return false.
  11. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
  12. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
  13. Return true if x and y refer to the same object or if they refer to objects joined to each other (see 13.1.2). Otherwise, return false.
Interesting is step 11. Yes, strings are treated as value types. But this does not explain why new String("a") !== "a". Do we have a browser not conforming to ECMA-262?
Not so fast!
Let's check the types of the operands. Try it out for yourself by wrapping them in typeof(). I find that new String("a") is an object, and step 1 is used: return false if the types are different.
If you wonder why new String("a") does not return a string, how about some exercise reading a specification? Have fun!
Aidiakapi wrote this in a comment below:
From the specification
11.2.2 The new Operator:
If Type(constructor) is not Object, throw a TypeError exception.
With other words, if String wouldn't be of type Object it couldn't be used with the new operator.
new always returns an Object, even for String constructors, too. And alas! The value semantics for strings (see step 11) is lost.
And this finally means: new String("a") !== "a".
I tested this in Firefox with Firebug using code like this:
console.time("testEquality");
var n = 0;
while (true) {
n++;
if (n == 100000)
break;
}
console.timeEnd("testEquality");
and
console.time("testTypeEquality");
var n = 0;
while (true) {
n++;
if (n === 100000)
break;
}
console.timeEnd("testTypeEquality");
My results (tested five times each and averaged):
==: 115.2
===: 114.4
So I'd say that the miniscule difference (this is over 100000 iterations, remember) is negligible. Performance isn't a reason to do ===. Type safety (well, as safe as you're going to get in JavaScript), and code quality is.
In PHP and JavaScript, it is a strict equality operator. Which means, it will compare both type and values.
In JavaScript it means of the same value and type.
For example,
4 == "4" // will return true
but
4 === "4" // will return false
Why == is so unpredictable?
What do you get when you compare an empty string "" with the number zero 0?
true
Yep, that's right according to == an empty string and the number zero are the same time.
And it doesn't end there, here's another one:
'0' == false // true
Things get really weird with arrays.
[1] == true // true
[] == false // true
[[]] == false // true
[0] == false // true
Then weirder with strings
[1,2,3] == '1,2,3' // true - REALLY?!
'\r\n\t' == 0 // true - Come on!
It get's worse:
When is equal not equal?
let A = '' // empty string
let B = 0 // zero
let C = '0' // zero string
A == B // true - ok...
B == C // true - so far so good...
A == C // **FALSE** - Plot twist!
Let me say that again:
(A == B) && (B == C) // true
(A == C) // **FALSE**
And this is just the crazy stuff you get with primitives.
It's a whole new level of crazy when you use == with objects.
At this point your probably wondering...
Why does this happen?
Well it's because unlike "triple equals" (===) which just checks if two values are the same.
== does a whole bunch of other stuff.
It has special handling for functions, special handling for nulls, undefined, strings, you name it.
It get's pretty wacky.
In fact, if you tried to write a function that does what == does it would look something like this:
function isEqual(x, y) { // if `==` were a function
if(typeof y === typeof x) return y === x;
// treat null and undefined the same
var xIsNothing = (y === undefined) || (y === null);
var yIsNothing = (x === undefined) || (x === null);
if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);
if(typeof y === "function" || typeof x === "function") {
// if either value is a string
// convert the function into a string and compare
if(typeof x === "string") {
return x === y.toString();
} else if(typeof y === "string") {
return x.toString() === y;
}
return false;
}
if(typeof x === "object") x = toPrimitive(x);
if(typeof y === "object") y = toPrimitive(y);
if(typeof y === typeof x) return y === x;
// convert x and y into numbers if they are not already use the "+" trick
if(typeof x !== "number") x = +x;
if(typeof y !== "number") y = +y;
// actually the real `==` is even more complicated than this, especially in ES6
return x === y;
}
function toPrimitive(obj) {
var value = obj.valueOf();
if(obj !== value) return value;
return obj.toString();
}
So what does this mean?
It means == is complicated.
Because it's complicated it's hard to know what's going to happen when you use it.
Which means you could end up with bugs.
So the moral of the story is...
Make your life less complicated.
Use === instead of ==.
The End.
The === operator is called a strict comparison operator, it does differ from the == operator.
Lets take 2 vars a and b.
For "a == b" to evaluate to true a and b need to be the same value.
In the case of "a === b" a and b must be the same value and also the same type for it to evaluate to true.
Take the following example
var a = 1;
var b = "1";
if (a == b) //evaluates to true as a and b are both 1
{
alert("a == b");
}
if (a === b) //evaluates to false as a is not the same type as b
{
alert("a === b");
}
In summary; using the == operator might evaluate to true in situations where you do not want it to so using the === operator would be safer.
In the 90% usage scenario it won't matter which one you use, but it is handy to know the difference when you get some unexpected behaviour one day.
=== checks same sides are equal in type as well as value.
Example:
'1' === 1 // will return "false" because `string` is not a `number`
Common example:
0 == '' // will be "true", but it's very common to want this check to be "false"
Another common example:
null == undefined // returns "true", but in most cases a distinction is necessary
Many times an untyped check would be handy because you do not care if the value is either undefined, null, 0 or ""
Javascript execution flow diagram for strict equality / Comparison '==='
Javascript execution flow diagram for non strict equality / comparison '=='
JavaScript === vs == .
0==false // true
0===false // false, because they are of a different type
1=="1" // true, auto type coercion
1==="1" // false, because they are of a different type
It means equality without type coercion
type coercion means JavaScript do not automatically convert any other data types to string data types
0==false // true,although they are different types
0===false // false,as they are different types
2=='2' //true,different types,one is string and another is integer but
javaScript convert 2 to string by using == operator
2==='2' //false because by using === operator ,javaScript do not convert
integer to string
2===2 //true because both have same value and same types
In a typical script there will be no performance difference. More important may be the fact that thousand "===" is 1 KB heavier than thousand "==" :) JavaScript profilers can tell you if there is a performance difference in your case.
But personally I would do what JSLint suggests. This recommendation is there not because of performance issues, but because type coercion means ('\t\r\n' == 0) is true.
The equal comparison operator == is confusing and should be avoided.
If you HAVE TO live with it, then remember the following 3 things:
It is not transitive: (a == b) and (b == c) does not lead to (a == c)
It's mutually exclusive to its negation: (a == b) and (a != b) always hold opposite Boolean values, with all a and b.
In case of doubt, learn by heart the following truth table:
EQUAL OPERATOR TRUTH TABLE IN JAVASCRIPT
Each row in the table is a set of 3 mutually "equal" values, meaning that any 2 values among them are equal using the equal == sign*
** STRANGE: note that any two values on the first column are not equal in that sense.**
'' == 0 == false // Any two values among these 3 ones are equal with the == operator
'0' == 0 == false // Also a set of 3 equal values, note that only 0 and false are repeated
'\t' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\r' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\t\r\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
null == undefined // These two "default" values are not-equal to any of the listed values above
NaN // NaN is not equal to any thing, even to itself.
There is unlikely to be any performance difference between the two operations in your usage. There is no type-conversion to be done because both parameters are already the same type. Both operations will have a type comparison followed by a value comparison.
Simply
== means comparison between operands with type coercion
and
=== means comparison between operands without type coercion.
Type coercion in JavaScript means automatically converting data types to other data types.
For example:
123 == "123" // Returns true, because JS coerces string "123" to number 123
// and then goes on to compare `123 == 123`.
123 === "123" // Returns false, because JS does not coerce values of different types here.
Yes! It does matter.
=== operator in javascript checks value as well as type where as == operator just checks the value (does type conversion if required).
You can easily test it. Paste following code in an HTML file and open it in browser
<script>
function onPageLoad()
{
var x = "5";
var y = 5;
alert(x === 5);
};
</script>
</head>
<body onload='onPageLoad();'>
You will get 'false' in alert. Now modify the onPageLoad() method to alert(x == 5); you will get true.
As a rule of thumb, I would generally use === instead of == (and !== instead of !=).
Reasons are explained in in the answers above and also Douglas Crockford is pretty clear about it (JavaScript: The Good Parts).
However there is one single exception:
== null is an efficient way to check for 'is null or undefined':
if( value == null ){
// value is either null or undefined
}
For example jQuery 1.9.1 uses this pattern 43 times, and the JSHint syntax checker even provides the eqnull relaxing option for this reason.
From the jQuery style guide:
Strict equality checks (===) should be used in favor of ==. The only
exception is when checking for undefined and null by way of null.
// Check for both undefined and null values, for some important reason.
undefOrNull == null;
EDIT 2021-03:
Nowadays most browsers
support the Nullish coalescing operator (??)
and the Logical nullish assignment (??=), which allows a more concise way to
assign a default value if a variable is null or undefined, for example:
if (a.speed == null) {
// Set default if null or undefined
a.speed = 42;
}
can be written as any of these forms
a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;
It's a strict check test.
It's a good thing especially if you're checking between 0 and false and null.
For example, if you have:
$a = 0;
Then:
$a==0;
$a==NULL;
$a==false;
All returns true and you may not want this. Let's suppose you have a function that can return the 0th index of an array or false on failure. If you check with "==" false, you can get a confusing result.
So with the same thing as above, but a strict test:
$a = 0;
$a===0; // returns true
$a===NULL; // returns false
$a===false; // returns false
=== operator checks the values as well as the types of the variables for equality.
== operator just checks the value of the variables for equality.
JSLint sometimes gives you unrealistic reasons to modify stuff. === has exactly the same performance as == if the types are already the same.
It is faster only when the types are not the same, in which case it does not try to convert types but directly returns a false.
So, IMHO, JSLint maybe used to write new code, but useless over-optimizing should be avoided at all costs.
Meaning, there is no reason to change == to === in a check like if (a == 'test') when you know it for a fact that a can only be a String.
Modifying a lot of code that way wastes developers' and reviewers' time and achieves nothing.
A simple example is
2 == '2' -> true, values are SAME because of type conversion.
2 === '2' -> false, values are NOT SAME because of no type conversion.
The top 2 answers both mentioned == means equality and === means identity. Unfortunately, this statement is incorrect.
If both operands of == are objects, then they are compared to see if they are the same object. If both operands point to the same object, then the equal operator returns true. Otherwise,
the two are not equal.
var a = [1, 2, 3];
var b = [1, 2, 3];
console.log(a == b) // false
console.log(a === b) // false
In the code above, both == and === get false because a and b are not the same objects.
That's to say: if both operands of == are objects, == behaves same as ===, which also means identity. The essential difference of this two operators is about type conversion. == has conversion before it checks equality, but === does not.
The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...
var x = 0;
var isTrue = x == null;
var isFalse = x === null;
Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...
CString x;
delete x;
Which obviously during runtime does very undefined things...
Google for implicit conversions in C++ and STL to get some of the arguments against it...
From the core javascript reference
=== Returns true if the operands are strictly equal (see above)
with no type conversion.
Equality comparison:
Operator ==
Returns true, when both operands are equal. The operands are converted to the same type before being compared.
>>> 1 == 1
true
>>> 1 == 2
false
>>> 1 == '1'
true
Equality and type comparison:
Operator ===
Returns true if both operands are equal and of the same type. It's generally
better and safer if you compare this way, because there's no behind-the-scenes type conversions.
>>> 1 === '1'
false
>>> 1 === 1
true
Here is a handy comparison table that shows the conversions that happen and the differences between == and ===.
As the conclusion states:
"Use three equals unless you fully understand the conversions that take
place for two-equals."
http://dorey.github.io/JavaScript-Equality-Table/
null and undefined are nothingness, that is,
var a;
var b = null;
Here a and b do not have values. Whereas, 0, false and '' are all values. One thing common beween all these are that they are all falsy values, which means they all satisfy falsy conditions.
So, the 0, false and '' together form a sub-group. And on other hand, null & undefined form the second sub-group. Check the comparisons in the below image. null and undefined would equal. The other three would equal to each other. But, they all are treated as falsy conditions in JavaScript.
This is same as any object (like {}, arrays, etc.), non-empty string & Boolean true are all truthy conditions. But, they are all not equal.

type checking in javascript

How can I check if a variable is currently an integer type? I've looked for some sort of resource for this and I think the === operator is important, but I'm not sure how to check if a variable is an Integer (or an Array for that matter)
A variable will never be an integer type in JavaScript — it doesn't distinguish between different types of Number.
You can test if the variable contains a number, and if that number is an integer.
(typeof foo === "number") && Math.floor(foo) === foo
If the variable might be a string containing an integer and you want to see if that is the case:
foo == parseInt(foo, 10)
These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:
js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false
A number is an integer if its modulo %1 is 0-
function isInt(n){
return (typeof n== 'number' && n%1== 0);
}
This is only as good as javascript gets- say +- ten to the 15th.
isInt(Math.pow(2,50)+.1) returns true, as does
Math.pow(2,50)+.1 == Math.pow(2,50)
A clean approach
You can consider using a very small, dependency-free library like Issable. Solves all problems:
// at the basic level it supports primitives
let number = 10
let array = []
is(number).number() // returns true
is(array).number() // throws error
// so you need to define your own:
import { define } from 'issable'
// or require syntax
const { define } = require('issable')
define({
primitives: 'number',
nameOfTyping: 'integer',
toPass: function(candidate) {
// pre-ECMA6
return candidate.toFixed(0) === candidate.toString()
// ECMA6
return Number.isInteger(candidate)
}
})
is(4.4).custom('integer') // throws error
is(8).customer('integer') // returns true
If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.
function test (string, boolean) {
// any of these below will throw errors to protect you
is(string).string()
is(boolean).boolean()
// continue with your code.
}
I know you're interested in Integer numbers so I won't re answer that but if you ever wanted to check for Floating Point numbers you could do this.
function isFloat( x )
{
return ( typeof x === "number" && Math.abs( x % 1 ) > 0);
}
Note: This MAY treat numbers ending in .0 (or any logically equivalent number of 0's) as an INTEGER. It actually needs a floating point precision error to occur to detect the floating point values in that case.
Ex.
alert(isFloat(5.2)); //returns true
alert(isFloat(5)); //returns false
alert(isFloat(5.0)); //return could be either true or false
Quite a few utility libraries such as YourJS offer functions for determining if something is an array or if something is an integer or a lot of other types as well. YourJS defines isInt by checking if the value is a number and then if it is divisible by 1:
function isInt(x) {
return typeOf(x, 'Number') && x % 1 == 0;
}
The above snippet was taken from this YourJS snippet and thusly only works because typeOf is defined by the library. You can download a minimalistic version of YourJS which mainly only has type checking functions such as typeOf(), isInt() and isArray(): http://yourjs.com/snippets/build/34,2
You may also have a look on Runtyper - a tool that performs type checking of operands in === (and other operations).
For your example, if you have strict comparison x === y and x = 123, y = "123", it will automatically check typeof x, typeof y and show warning in console:
Strict compare of different types: 123 (number) === "123" (string)
Try this code:
alert(typeof(1) == "number");

When to use equality ("==") instead of identity ("===")? [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace == (two equals signs) with === (three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement.
Is there a performance benefit to replacing == with ===?
Any performance improvement would be welcomed as many comparison operators exist.
If no type conversion takes place, would there be a performance gain over ==?
The strict equality operator (===) behaves identically to the abstract equality operator (==) except no type conversion is done, and the types must be the same to be considered equal.
Reference: JavaScript Tutorial: Comparison Operators
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.
To quote Douglas Crockford's excellent JavaScript: The Good Parts,
JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. The rules by which they do that are complicated and unmemorable. These are some of the interesting cases:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true
The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.
Update
A good point was brought up by #Casebash in the comments and in #Phillipe Laybaert's answer concerning objects. For objects, == and === act consistently with one another (except in a special case).
var a = [1,2,3];
var b = [1,2,3];
var c = { x: 1, y: 2 };
var d = { x: 1, y: 2 };
var e = "text";
var f = "te" + "xt";
a == b // false
a === b // false
c == d // false
c === d // false
e == f // true
e === f // true
The special case is when you compare a primitive with an object that evaluates to the same primitive, due to its toString or valueOf method. For example, consider the comparison of a string primitive with a string object created using the String constructor.
"abc" == new String("abc") // true
"abc" === new String("abc") // false
Here the == operator is checking the values of the two objects and returning true, but the === is seeing that they're not the same type and returning false. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the String constructor to create string objects from string literals.
Reference
https://262.ecma-international.org/5.1/#sec-11.9.3
Using the == operator (Equality)
true == 1; //true, because 'true' is converted to 1 and then compared
"2" == 2; //true, because "2" is converted to 2 and then compared
Using the === operator (Identity)
true === 1; //false
"2" === 2; //false
This is because the equality operator == does type coercion, meaning that the interpreter implicitly tries to convert the values before comparing.
On the other hand, the identity operator === does not do type coercion, and thus does not convert the values when comparing.
Here's an interesting visualisation of the equality comparison between == and ===.
Source: https://github.com/dorey/JavaScript-Equality-Table (demo, unified demo)
var1 === var2
When using === for JavaScript equality testing, everything is as is.
Nothing gets converted before being evaluated.
var1 == var2
When using == for JavaScript equality testing, some funky conversions take place.
Summary of equality in Javascript
Conclusion:
Always use ===, unless you fully understand the funky conversions that take place with ==.
In the answers here, I didn't read anything about what equal means. Some will say that === means equal and of the same type, but that's not really true. It actually means that both operands reference the same object, or in case of value types, have the same value.
So, let's take the following code:
var a = [1,2,3];
var b = [1,2,3];
var c = a;
var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true
The same here:
var a = { x: 1, y: 2 };
var b = { x: 1, y: 2 };
var c = a;
var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true
Or even:
var a = { };
var b = { };
var c = a;
var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true
This behavior is not always obvious. There's more to the story than being equal and being of the same type.
The rule is:
For value types (numbers):
a === b returns true if a and b have the same value and are of the same type
For reference types:
a === b returns true if a and b reference the exact same object
For strings:
a === b returns true if a and b are both strings and contain the exact same characters
Strings: the special case...
Strings are not value types, but in Javascript they behave like value types, so they will be "equal" when the characters in the string are the same and when they are of the same length (as explained in the third rule)
Now it becomes interesting:
var a = "12" + "3";
var b = "123";
alert(a === b); // returns true, because strings behave like value types
But how about this?:
var a = new String("123");
var b = "123";
alert(a === b); // returns false !! (but they are equal and of the same type)
I thought strings behave like value types? Well, it depends who you ask... In this case a and b are not the same type. a is of type Object, while b is of type string. Just remember that creating a string object using the String constructor creates something of type Object that behaves as a string most of the time.
Let me add this counsel:
If in doubt, read the specification!
ECMA-262 is the specification for a scripting language of which JavaScript is a dialect. Of course in practice it matters more how the most important browsers behave than an esoteric definition of how something is supposed to be handled. But it is helpful to understand why new String("a") !== "a".
Please let me explain how to read the specification to clarify this question. I see that in this very old topic nobody had an answer for the very strange effect. So, if you can read a specification, this will help you in your profession tremendously. It is an acquired skill. So, let's continue.
Searching the PDF file for === brings me to page 56 of the specification: 11.9.4. The Strict Equals Operator ( === ), and after wading through the specificationalese I find:
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
  1. If Type(x) is different from Type(y), return false.
  2. If Type(x) is Undefined, return true.
  3. If Type(x) is Null, return true.
  4. If Type(x) is not Number, go to step 11.
  5. If x is NaN, return false.
  6. If y is NaN, return false.
  7. If x is the same number value as y, return true.
  8. If x is +0 and y is −0, return true.
  9. If x is −0 and y is +0, return true.
  10. Return false.
  11. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
  12. If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
  13. Return true if x and y refer to the same object or if they refer to objects joined to each other (see 13.1.2). Otherwise, return false.
Interesting is step 11. Yes, strings are treated as value types. But this does not explain why new String("a") !== "a". Do we have a browser not conforming to ECMA-262?
Not so fast!
Let's check the types of the operands. Try it out for yourself by wrapping them in typeof(). I find that new String("a") is an object, and step 1 is used: return false if the types are different.
If you wonder why new String("a") does not return a string, how about some exercise reading a specification? Have fun!
Aidiakapi wrote this in a comment below:
From the specification
11.2.2 The new Operator:
If Type(constructor) is not Object, throw a TypeError exception.
With other words, if String wouldn't be of type Object it couldn't be used with the new operator.
new always returns an Object, even for String constructors, too. And alas! The value semantics for strings (see step 11) is lost.
And this finally means: new String("a") !== "a".
I tested this in Firefox with Firebug using code like this:
console.time("testEquality");
var n = 0;
while (true) {
n++;
if (n == 100000)
break;
}
console.timeEnd("testEquality");
and
console.time("testTypeEquality");
var n = 0;
while (true) {
n++;
if (n === 100000)
break;
}
console.timeEnd("testTypeEquality");
My results (tested five times each and averaged):
==: 115.2
===: 114.4
So I'd say that the miniscule difference (this is over 100000 iterations, remember) is negligible. Performance isn't a reason to do ===. Type safety (well, as safe as you're going to get in JavaScript), and code quality is.
In PHP and JavaScript, it is a strict equality operator. Which means, it will compare both type and values.
In JavaScript it means of the same value and type.
For example,
4 == "4" // will return true
but
4 === "4" // will return false
Why == is so unpredictable?
What do you get when you compare an empty string "" with the number zero 0?
true
Yep, that's right according to == an empty string and the number zero are the same time.
And it doesn't end there, here's another one:
'0' == false // true
Things get really weird with arrays.
[1] == true // true
[] == false // true
[[]] == false // true
[0] == false // true
Then weirder with strings
[1,2,3] == '1,2,3' // true - REALLY?!
'\r\n\t' == 0 // true - Come on!
It get's worse:
When is equal not equal?
let A = '' // empty string
let B = 0 // zero
let C = '0' // zero string
A == B // true - ok...
B == C // true - so far so good...
A == C // **FALSE** - Plot twist!
Let me say that again:
(A == B) && (B == C) // true
(A == C) // **FALSE**
And this is just the crazy stuff you get with primitives.
It's a whole new level of crazy when you use == with objects.
At this point your probably wondering...
Why does this happen?
Well it's because unlike "triple equals" (===) which just checks if two values are the same.
== does a whole bunch of other stuff.
It has special handling for functions, special handling for nulls, undefined, strings, you name it.
It get's pretty wacky.
In fact, if you tried to write a function that does what == does it would look something like this:
function isEqual(x, y) { // if `==` were a function
if(typeof y === typeof x) return y === x;
// treat null and undefined the same
var xIsNothing = (y === undefined) || (y === null);
var yIsNothing = (x === undefined) || (x === null);
if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);
if(typeof y === "function" || typeof x === "function") {
// if either value is a string
// convert the function into a string and compare
if(typeof x === "string") {
return x === y.toString();
} else if(typeof y === "string") {
return x.toString() === y;
}
return false;
}
if(typeof x === "object") x = toPrimitive(x);
if(typeof y === "object") y = toPrimitive(y);
if(typeof y === typeof x) return y === x;
// convert x and y into numbers if they are not already use the "+" trick
if(typeof x !== "number") x = +x;
if(typeof y !== "number") y = +y;
// actually the real `==` is even more complicated than this, especially in ES6
return x === y;
}
function toPrimitive(obj) {
var value = obj.valueOf();
if(obj !== value) return value;
return obj.toString();
}
So what does this mean?
It means == is complicated.
Because it's complicated it's hard to know what's going to happen when you use it.
Which means you could end up with bugs.
So the moral of the story is...
Make your life less complicated.
Use === instead of ==.
The End.
The === operator is called a strict comparison operator, it does differ from the == operator.
Lets take 2 vars a and b.
For "a == b" to evaluate to true a and b need to be the same value.
In the case of "a === b" a and b must be the same value and also the same type for it to evaluate to true.
Take the following example
var a = 1;
var b = "1";
if (a == b) //evaluates to true as a and b are both 1
{
alert("a == b");
}
if (a === b) //evaluates to false as a is not the same type as b
{
alert("a === b");
}
In summary; using the == operator might evaluate to true in situations where you do not want it to so using the === operator would be safer.
In the 90% usage scenario it won't matter which one you use, but it is handy to know the difference when you get some unexpected behaviour one day.
=== checks same sides are equal in type as well as value.
Example:
'1' === 1 // will return "false" because `string` is not a `number`
Common example:
0 == '' // will be "true", but it's very common to want this check to be "false"
Another common example:
null == undefined // returns "true", but in most cases a distinction is necessary
Many times an untyped check would be handy because you do not care if the value is either undefined, null, 0 or ""
Javascript execution flow diagram for strict equality / Comparison '==='
Javascript execution flow diagram for non strict equality / comparison '=='
JavaScript === vs == .
0==false // true
0===false // false, because they are of a different type
1=="1" // true, auto type coercion
1==="1" // false, because they are of a different type
It means equality without type coercion
type coercion means JavaScript do not automatically convert any other data types to string data types
0==false // true,although they are different types
0===false // false,as they are different types
2=='2' //true,different types,one is string and another is integer but
javaScript convert 2 to string by using == operator
2==='2' //false because by using === operator ,javaScript do not convert
integer to string
2===2 //true because both have same value and same types
In a typical script there will be no performance difference. More important may be the fact that thousand "===" is 1 KB heavier than thousand "==" :) JavaScript profilers can tell you if there is a performance difference in your case.
But personally I would do what JSLint suggests. This recommendation is there not because of performance issues, but because type coercion means ('\t\r\n' == 0) is true.
The equal comparison operator == is confusing and should be avoided.
If you HAVE TO live with it, then remember the following 3 things:
It is not transitive: (a == b) and (b == c) does not lead to (a == c)
It's mutually exclusive to its negation: (a == b) and (a != b) always hold opposite Boolean values, with all a and b.
In case of doubt, learn by heart the following truth table:
EQUAL OPERATOR TRUTH TABLE IN JAVASCRIPT
Each row in the table is a set of 3 mutually "equal" values, meaning that any 2 values among them are equal using the equal == sign*
** STRANGE: note that any two values on the first column are not equal in that sense.**
'' == 0 == false // Any two values among these 3 ones are equal with the == operator
'0' == 0 == false // Also a set of 3 equal values, note that only 0 and false are repeated
'\t' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\r' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
'\t\r\n' == 0 == false // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
null == undefined // These two "default" values are not-equal to any of the listed values above
NaN // NaN is not equal to any thing, even to itself.
There is unlikely to be any performance difference between the two operations in your usage. There is no type-conversion to be done because both parameters are already the same type. Both operations will have a type comparison followed by a value comparison.
Simply
== means comparison between operands with type coercion
and
=== means comparison between operands without type coercion.
Type coercion in JavaScript means automatically converting data types to other data types.
For example:
123 == "123" // Returns true, because JS coerces string "123" to number 123
// and then goes on to compare `123 == 123`.
123 === "123" // Returns false, because JS does not coerce values of different types here.
Yes! It does matter.
=== operator in javascript checks value as well as type where as == operator just checks the value (does type conversion if required).
You can easily test it. Paste following code in an HTML file and open it in browser
<script>
function onPageLoad()
{
var x = "5";
var y = 5;
alert(x === 5);
};
</script>
</head>
<body onload='onPageLoad();'>
You will get 'false' in alert. Now modify the onPageLoad() method to alert(x == 5); you will get true.
As a rule of thumb, I would generally use === instead of == (and !== instead of !=).
Reasons are explained in in the answers above and also Douglas Crockford is pretty clear about it (JavaScript: The Good Parts).
However there is one single exception:
== null is an efficient way to check for 'is null or undefined':
if( value == null ){
// value is either null or undefined
}
For example jQuery 1.9.1 uses this pattern 43 times, and the JSHint syntax checker even provides the eqnull relaxing option for this reason.
From the jQuery style guide:
Strict equality checks (===) should be used in favor of ==. The only
exception is when checking for undefined and null by way of null.
// Check for both undefined and null values, for some important reason.
undefOrNull == null;
EDIT 2021-03:
Nowadays most browsers
support the Nullish coalescing operator (??)
and the Logical nullish assignment (??=), which allows a more concise way to
assign a default value if a variable is null or undefined, for example:
if (a.speed == null) {
// Set default if null or undefined
a.speed = 42;
}
can be written as any of these forms
a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;
It's a strict check test.
It's a good thing especially if you're checking between 0 and false and null.
For example, if you have:
$a = 0;
Then:
$a==0;
$a==NULL;
$a==false;
All returns true and you may not want this. Let's suppose you have a function that can return the 0th index of an array or false on failure. If you check with "==" false, you can get a confusing result.
So with the same thing as above, but a strict test:
$a = 0;
$a===0; // returns true
$a===NULL; // returns false
$a===false; // returns false
=== operator checks the values as well as the types of the variables for equality.
== operator just checks the value of the variables for equality.
JSLint sometimes gives you unrealistic reasons to modify stuff. === has exactly the same performance as == if the types are already the same.
It is faster only when the types are not the same, in which case it does not try to convert types but directly returns a false.
So, IMHO, JSLint maybe used to write new code, but useless over-optimizing should be avoided at all costs.
Meaning, there is no reason to change == to === in a check like if (a == 'test') when you know it for a fact that a can only be a String.
Modifying a lot of code that way wastes developers' and reviewers' time and achieves nothing.
A simple example is
2 == '2' -> true, values are SAME because of type conversion.
2 === '2' -> false, values are NOT SAME because of no type conversion.
The top 2 answers both mentioned == means equality and === means identity. Unfortunately, this statement is incorrect.
If both operands of == are objects, then they are compared to see if they are the same object. If both operands point to the same object, then the equal operator returns true. Otherwise,
the two are not equal.
var a = [1, 2, 3];
var b = [1, 2, 3];
console.log(a == b) // false
console.log(a === b) // false
In the code above, both == and === get false because a and b are not the same objects.
That's to say: if both operands of == are objects, == behaves same as ===, which also means identity. The essential difference of this two operators is about type conversion. == has conversion before it checks equality, but === does not.
The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...
var x = 0;
var isTrue = x == null;
var isFalse = x === null;
Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...
CString x;
delete x;
Which obviously during runtime does very undefined things...
Google for implicit conversions in C++ and STL to get some of the arguments against it...
From the core javascript reference
=== Returns true if the operands are strictly equal (see above)
with no type conversion.
Equality comparison:
Operator ==
Returns true, when both operands are equal. The operands are converted to the same type before being compared.
>>> 1 == 1
true
>>> 1 == 2
false
>>> 1 == '1'
true
Equality and type comparison:
Operator ===
Returns true if both operands are equal and of the same type. It's generally
better and safer if you compare this way, because there's no behind-the-scenes type conversions.
>>> 1 === '1'
false
>>> 1 === 1
true
Here is a handy comparison table that shows the conversions that happen and the differences between == and ===.
As the conclusion states:
"Use three equals unless you fully understand the conversions that take
place for two-equals."
http://dorey.github.io/JavaScript-Equality-Table/
null and undefined are nothingness, that is,
var a;
var b = null;
Here a and b do not have values. Whereas, 0, false and '' are all values. One thing common beween all these are that they are all falsy values, which means they all satisfy falsy conditions.
So, the 0, false and '' together form a sub-group. And on other hand, null & undefined form the second sub-group. Check the comparisons in the below image. null and undefined would equal. The other three would equal to each other. But, they all are treated as falsy conditions in JavaScript.
This is same as any object (like {}, arrays, etc.), non-empty string & Boolean true are all truthy conditions. But, they are all not equal.

Categories

Resources