This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Javascript === vs ==
What's the diff between "===" and "==" ? Thanks!
'===' means equality without type coersion. In other words, if using the triple equals, the values must be equal in type as well.
e.g.
0==false // true
0===false // false, because they are of a different type
1=="1" // true, auto type coersion
1==="1" // false, because they are of a different type
Source: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html
Ripped from my blog: keithdonegan.com
The Equality Operator (==)
The equality operator (==) checks whether two operands are the same and returns true if they are the same and false if they are different.
The Identity Operator (===)
The identity operator checks whether two operands are “identical”.
These rules determine whether two values are identical:
They have to have the same type.
If number values have the same value they are identical, unless one or both are NaN.
If string values have the same value they are identical, unless the strings differ in length or content.
If both values refer to the same object, array or function they are identical.
If both values are null or undefined they are identical.
The === operator means "is exactly equal to," matching by both value and data type.
The == operator means "is equal to," matching by value only.
It tests exact equality of both value and type.
given the assignment
x = 7
x===7 is true
x==="7" is false
In a nutshell "===" tests for the equality of value AND of type:
From here:
Related
Quick and a silly question that got me confused.
What kind of error occurs if I use an assignment statement instead of a comparison statement? I need to check if the value of the counter variable is equal to 5.
The code:
if (counter = 5) { /* ==SOME CODE==*/}
VS
if (counter == 5) { /* ==SOME CODE==*/}
The easiest way to pick-up this problem is to reverse the order of the comparison.
Instead of:
if (someVar == 5)
Use:
if (5 == someVar)
This way, if you mess it up, you'll get an assignment error, since you can't assign a different value to the number 5. You can assign a different value to a number object that happens to hold the number 5, but you can't change the 5 itself. ;)
What kind of error occurs if I use an assignment statement instead of a comparison statement?
In your example i assume that a browser would not throw any errors.
I tested https://validatejavascript.com/ with this code:
let counter = 3;
if (counter = 5) {
alert('Will this ever show or always?');
}
A linter might generate a warning - for exmaple
validatejavascript.com threw: 3:5 error Unexpected assignment within an 'if' statement. (no-cond-assign) and
jshint.com threw: Expected a conditional expression and instead saw an assignment.
And based on your comment:
But I need to check if the value of the counter variable is equal to 5.
A simple assignment operator (=) is used to assign a value to a variable.
What you are looking for are operators for Equality comparisons and sameness
JavaScript provides three different value-comparison operations:
=== - Strict Equality Comparison ("strict equality", "identity", "triple equals")
== - Abstract Equality Comparison ("loose equality", "double equals")
Object.is provides SameValue (new in ES2015).
Which operation you choose depends on what sort of comparison you are
looking to perform. Briefly:
double equals (==) will perform a type conversion
when comparing two things, and will handle NaN, -0, and +0
specially to conform to IEEE 754 (so NaN != NaN, and -0 == +0);
triple equals (===) will do the same comparison as double equals
(including the special handling for NaN, -0, and +0)
but without type conversion; if the types differ, false is returned.
Object.is does no type conversion and no special handling for NaN, -0,
and +0 (giving it the same behavior as === except on those special
numeric values).
Note that the distinction between these all have to do with their
handling of primitives; none of them compares whether the parameters
are conceptually similar in structure. For any non-primitive objects x
and y which have the same structure but are distinct objects
themselves, all of the above forms will evaluate to false.
This question already has answers here:
Why NaN is greater than any number in JavaScript? [duplicate]
(2 answers)
Closed 4 years ago.
I am trying to make some conditional statements while trying to solve a coding challenge. I have kept track of all the occurrences of letters of two strings in different objects. When I try to compare them by their counts if the count is undefined in the other object it evaluates to false even though the first value is truthy.
However;
1 > Boolean(undefined) evaluates to true. However 1 > undefined evaluates to false. Is there reason why the behavior is so ?
Javascript does a lot of funky casting when you compare things together that usually shouldn't be comparable.
1>undefined casts undefined to a NaN, and you can't compare a number to a Not a Number so any comparison will return false >,<,== etc
When you do 1>Boolean(undefined) undefined is cast to its boolean equivalent false, then when it's compared it will be cast to a 0, you can confirm this by doing Number(Boolean(undefined)) and since 1 is bigger than 0 it returns true.
In order to use the comparison operator >, both operands must be numeric. 1 already is, so Boolean(undefined) (which evaluates to false by the way) must be converted to a number. When it is, you get 0.
// First, convert undefined to a Boolean
let bool = Boolean(undefined)
console.log(bool);
// Then convert that to a number
let num = Number(bool);
console.log(num);
So, 1 > 0 is true.
Things to understand:
JavaScript is a "loosely" or "weakly" typed language. This means that data can, and often is, implicitly converted (coerced) into a different type category.
All data can be classified as "truthy" or "falsy", which means that if converted to a Boolean, would it convert to true or false. Things like null, undefined, "", 0, false, and NaN are all "falsy". And false in JavaScript (and most other languages) converts to the number 0, while true usually converts to 1.
This question already has answers here:
Why does [NaN].includes(NaN) return true in JavaScript?
(5 answers)
Closed 24 days ago.
I'm learning about includes() feature, and I found this code
[NaN].includes(NaN) //True
But
NaN === NaN // False
Why this is posible?
Using equality NaN === NaN and using includes [NaN].includes(NaN) are basically asking two different questions:
Equality - are this things that have the same name are actually equal?
NaN is an amorphic entity, which describes the concept of not being a numeric value, and doesn't actually have a value you can compare. Equality uses the Strict Equality Comparison, and defines that a comparison x === y with NaN on any side of the equation is always false:
a. If x is NaN, return false.
b. If y is NaN, return false.
Includes - do I have something with that "name" in the array?
However, to search for a NaN in an array, and to keep the to Array#includes signature of passing only one param, and not a callback, we need a way to "name" what we are searching for. To make that possible, ccording to the Array#includes definition in the ECMAScript 2016 (ECMA-262) docs:
The includes method intentionally differs from the similar indexOf
method in two ways. First, it uses the SameValueZero algorithm,
instead of Strict Equality Comparison, allowing it to detect NaN
array elements. Second, it does not skip missing array elements,
instead treating them as undefined.
The definition of SameValueZero(x, y) states that when comparing:
If x is NaN and y is NaN, return true.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function.
[ NaN ].includes(NaN) what this does is to check if NaN is in the [ ].
NaN === NaN and NaN == NaN will still return the same value which is false. What you just have to know is that the includes methods checks if a value is the array it is been called on. Behind the hood i think the includes Array method does it's checks using typeof()
typeof(NaN) // number
[ NaN ].includes(NaN) // true
typeof("1") // string
[ 1 ].includes("1") // false
typeof(1) // number
[ 1 ].includes(1) // true
this is according to the SameValueZero Algorithm that the includes method uses. Internally it checks the type of the value
This question already has answers here:
Object.is vs ===
(6 answers)
Closed 5 years ago.
We know what the difference between == and === is - basically, === prevents Javascript engine to convert one of the parameter for making both parameters of the same type. But now, in ES6, came a new operator - Object.is which is a bit confusing (or maybe === is now confusing..)
From Mozila website (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) we can see the difference:
Sameness Comparisons:
x y == === Object.is
+0 -0 true true false
NaN NaN false false true
So, for me, looks like Object.is is even more strict in comparing parameters, if so, question raises - how unstrict was === (called "Strict Equality") :)
From the article you linked:
When to use Object.is versus triple equals
Aside from the way it treats NaN, generally, the only time Object.is's special behavior towards zeros is likely to be of interest is in the pursuit of certain meta-programming schemes, especially regarding property descriptors when it is desirable for your work to mirror some of the characteristics of Object.defineProperty. If your use case does not require this, it is suggested to avoid Object.is and use === instead. Even if your requirements involve having comparisons between two NaN values evaluate to true, generally it is easier to special-case the NaN checks (using the isNaN method available from previous versions of ECMAScript) than it is to work out how surrounding computations might affect the sign of any zeros you encounter in your comparison.
Via MDN:
This is also not the same as being equal according to the === operator. The === operator (and the == operator as well) treats the number values -0 and +0 as equal and treats Number.NaN as not equal to NaN.
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/