EN
JavaScript - what operator (== or ===) is used by switch statement to compare?
1 answers
8 points
As in the question title: What operator (==
or ===
) is used by switch statement to compare?
Is it safe to compare different objects using switch statement?
What about?:
xxxxxxxxxx
1
switch (object) {
2
// ...
3
case object1:
4
// ...
5
break;
6
case object2:
7
// ...
8
break;
9
case object3:
10
// ...
11
break;
12
// ...
13
default:
14
// ...
15
break;
16
}
1 answer
4 points
The switch
statement compares variables by values and its types, so it behaves like ===
operator and is safe when compare different objects.
e.g. 1:
xxxxxxxxxx
1
const object1 = {
2
toString: () => 'Object 1'
3
};
4
const object2 = {
5
toString: () => 'Object 2'
6
};
7
8
const object = object1;
9
10
switch (object) {
11
case object1: console.log('`===` operator was used with `object1`.'); break;
12
case object2: console.log('`===` operator was used with `object2`.'); break;
13
case 'Object 1': console.log('`toString()` method was used with `object1`.'); break;
14
case 'Object 2': console.log('`toString()` method was used with `object2`.'); break;
15
default:
16
throw new Error('Switch statement is not able to compare object in the correct way.');
17
}
Expected output:
xxxxxxxxxx
1
`===` operator was used with `object1`.
e.g. 2:
xxxxxxxxxx
1
const object1 = {
2
toString: () => 'Object 1'
3
};
4
const object2 = {
5
toString: () => 'Object 2'
6
};
7
8
const object = object1;
9
10
switch (object) {
11
case 'Object 1': console.log('`toString()` method was used with `object1`.'); break;
12
case 'Object 2': console.log('`toString()` method was used with `object2`.'); break;
13
case object1: console.log('`===` operator was used with `object1`.'); break;
14
case object2: console.log('`===` operator was used with `object2`.'); break;
15
default:
16
throw new Error('Switch statement is not able to compare object in the correct way.');
17
}
Expected output:
xxxxxxxxxx
1
`===` operator was used with `object1`.
e.g. 3:
xxxxxxxxxx
1
const value = '1';
2
3
switch (value) {
4
case 1:
5
console.log('Case 1 detected.');
6
break;
7
case '1':
8
console.log('Case 2 detected.');
9
break;
10
default:
11
throw new Error('Switch statement is not able to compare values in the correct way.');
12
}
Expected output:
xxxxxxxxxx
1
Case 2 detected.
0 commentsShow commentsAdd comment