Attention to these three operators:
= Assignement
== Equality
=== Strict equality
!!!One of the most common mistakes is to use the assignment operator instead of the equality operator, like:
var a = 1;
var b = 2;
if (a = b){
alert("They are equal"); //The code in the if statement will always be executed
}
This is an assignment and returns true, therefore the code in the if statement will always be executed!
Properly is to use the equality operator:
var a = 1;
var b = 1;
if (a == b){
alert("They are equal"); //The result will be: They are equal
} else {
alert("They are not equal");
}
But if we compare a numerical value to a string using the equality operator, the result will be the same, because they have same value:
var a = 1;
var b = "1";
if (a == b){
alert("They are equal"); //The result will be: They are equal
} else {
alert("They are not equal");
}
If we want to o check if they have the same value and the same type, we must use the strict equality operator, like:
var a = 1;
var b = "1";
if (a === b){
alert("They are equal");
} else {
alert("They are not equal"); //The result will be: They are not equal
}
In other words, this means that they are not just equal, they are identical!
? ternary operator
condition ? true : false
The ternary operator which is not very common, is similar to an if/else statement, the difference is that we can condense the code into a single line:
Example:
var a = 3;
if ( (a%2) == 0){
alert ("a is an even number");
} else{
alert ("a is not an even number"); //The result will be: a is not an even number
}
is similar with:
var a = 3;
((a%2) == 0) ? alert ("a is an even number") : alert ("a is not an even number");
//The result will be: a is not an even number
Type Operators
Can be used to find the data type of a JavaScript variable.
typeof |
returns the type of a variable |
instanceof |
returns true if an object is an instance of an object class |