Tuesday, April 15, 2014

How does === means different than == in JavaScript?

These two operators do not mean the same and does different operation too.
== verifies if the compared values are equal
=== verifies if the variables that are compared have the same value and are the same type
JavaScript's standard equality operators (== and !=) check if two expressions are equal (or not equal). If the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison. Values are considered equal if they are identical strings, numerically equivalent numbers, the same object, identical Boolean values, or (if different types) they can be coerced into one of these situations.
JavaScript's identity (strict equality) operators (=== and !==) behave identically to the equality operators except no type conversion is done, and the types must be the same to be considered equal. Here are a few examples:
"3" == 3 // true
"3" === 3 // false
1 == true // true
1 === true // false
"1" == true // true
"1" === true // false

Code snippet:

<script type="text/javascript">
var a = 5;
var b = '5';
var c = 5;
if(a==b)
{
document.write('a and b have the same value');
}

if(a===b)
{
document.write('a and b have the same value and the same type');
}
if(a===c)
{
document.write('a and c have the same value and the same type');
}
</script>


No comments :

Post a Comment