Equality in value and type in JavaScript
Suppose you want to compare in such a way that the number in quotes is not equal to the same number without quotes. In other words, you want to compare in such a way that the comparison is not only in value, but also in data type.
To do this, instead of the operator ==
,
you should use the operator ===
. In the
following example, when comparing the string
'3'
and the number 3
, the condition
will be false, since the variables, although
equal in value, are not equal in type:
if ('3' === 3) {
console.log('+++');
} else {
console.log('---'); // it will work
}
But when comparing two strings
'3'
the condition will be true:
if ('3' === '3') {
console.log('+++'); // it will work
} else {
console.log('---');
}
Just like when comparing numbers:
if (3 === 3) {
console.log('+++'); // it will work
} else {
console.log('---');
}
The difference between the operator ==
and the operator ===
appears exactly
when the values are the same but their data
types are different. In other cases, these
operators work the same way. For example,
when comparing different numbers, of course,
'---'
will be displayed:
if (2 === 3) {
console.log('+++');
} else {
console.log('---'); // it will work
}
Without running the code, determine what will be output to the console:
let test1 = '3';
let test2 = '3';
if (test1 == test2) {
console.log('+++');
} else {
console.log('---');
}
Without running the code, determine what will be output to the console:
let test1 = '3';
let test2 = '3';
if (test1 === test2) {
console.log('+++');
} else {
console.log('---');
}
Without running the code, determine what will be output to the console:
let test1 = 3;
let test2 = '3';
if (test1 == test2) {
console.log('+++');
} else {
console.log('---');
}
Without running the code, determine what will be output to the console:
let test1 = 3;
let test2 = '3';
if (test1 === test2) {
console.log('+++');
} else {
console.log('---');
}
Without running the code, determine what will be output to the console:
let test1 = 3;
let test2 = 3;
if (test1 === test2) {
console.log('+++');
} else {
console.log('---');
}