Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Explain Strict Comparison in JavaScript switch statement?
The JavaScript switch statement performs strict comparison (===) to match values. This means both value and type must be identical for a case to execute. If no strict match is found, the default case runs.
Understanding Strict Comparison
Strict comparison checks both value and type. For example, the number 1 is not equal to the string "1" in strict comparison:
Strict Comparison Demo
Switch Statement Example
Here's an example showing how switch performs strict comparison. When you enter a number in the input field, it becomes a string, so numeric cases won't match:
Switch Strict Comparison
JavaScript Switch Statement Strict Comparison
Enter day number (1-7):
Correct Implementation
To fix this, either compare with strings or convert the input to a number:
Fixed Switch Example
Enter day (1-7):
Key Points
- Switch uses strict comparison (
===), not loose comparison (==) - HTML input values are always strings, even when entering numbers
- Use
parseInt()orNumber()to convert strings to numbers - Alternatively, compare against string values in your cases
Conclusion
JavaScript switch statements always use strict comparison, requiring exact type and value matches. Convert data types appropriately or use string comparisons to avoid unexpected default case execution.
