I have seen many uses of "===" in conditional statements.
Can anyone tell me what does it mean?
something like ternary operator?
if(typeof(x) == "string")
{
x= (x=== "true");
}
I have seen many uses of "===" in conditional statements.
Can anyone tell me what does it mean?
something like ternary operator?
if(typeof(x) == "string")
{
x= (x=== "true");
}
The ===
operator checks for equality which means that the type
and value
are the same. The ==
operator checks for equivalence which means that the value
is the same and it disregards the type.
Example
alert("1" == 1); //alerts true
alert("1" === 1); //alerts false, types are different.
alert(1 === 1); //alerts true
This can be useful in Javascript due to the loosely typed nature of the language and the truthy/falsey nature of variables.
For example, an empty String is ==
false
("") ? alert(true): alert(false); //alerts false
You will also find that 0
is ==
false
(0) ? alert(true): alert(false); //alerts false
As well as an empty property on an object:
({}.prop) ? alert(true): alert(false); //alerts false
In these situations it may be necessary to use the ===
operator when type is important.
It's strict equality comparison
. It means that not just the value is evaluated but also the type of the objects. More info is available in the ECMAScript-specification.
The ===
mean "equality without type coercion". Using the triple equals both the values and their types must be equal.
"===" does not perform type conversion so it could have a different result than "==".
The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.