Change
switch(values) {
To
switch(true) {
switch checks with strict equality.
And use, if necessary some break if you do not want to fall through the switch cases (kudos to blex).
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › switch
switch - JavaScript - MDN Web Docs - Mozilla
In JavaScript, you can even mix in definitions of strings into these case statements as well. ... const foo = 1; let output = "Output: "; switch (foo) { case 0: output += "So "; case 1: output += "What "; output += "Is "; case 2: output += "Your "; case 3: output += "Name"; case 4: output += "?"; console.log(output); break; case 5: output += "!"; console.log(output); break; default: console.log("Please pick a number from 0 to 5!"); }
Top answer 1 of 3
30
Change
switch(values) {
To
switch(true) {
switch checks with strict equality.
And use, if necessary some break if you do not want to fall through the switch cases (kudos to blex).
2 of 3
0
You are using it like a function parameter which is unnecessary (and wrong). Since switch statements check that the value equals the case, you'll want to use:
switch(true)
Switch case with an object - JavaScript - SitePoint Forums | Web Development & Design Community
Hi All, I need some help with JS which is a part of a sigma grid ajax function. Here’s an array with variable names as MySql table column names : var dsOption= { fields :[ {name : 'username' }, {name : 'full_name' }, {name : 'userlevel' }, {name : 'email' }, {name : 'phone' } ], recordType ... More on sitepoint.com
Would it be faster (more optimized) to have use switch or an array of functions?
The specifications doesn't make a time complexity guarantee for switch as far as I know, so it would be harder to say which would be faster. Writing code wise, I think it would look much cleaner to go with array of functions. But better yet, why not use a look up table like a Map. It has a constant O(1) lookup time (almost all engines have implemented this). Assign functions to case values and look it up accordingly. More on reddit.com
Switch statement vs "An Alternate Approach"
This is in response to that "An Alternate Approach" from the other day. As I suspected, the Switch statement is much faster, so that article didn't really convince me, and I still don't know why people think it's for babies More on reddit.com
Deprecating the switch statement for Object literals
In my opinion, long if/else trees or switches are a code smell for not using the right level of abstraction. This might happen because you are writing low-level code like emulators or communication protocols that have a very procedural interface, but most people generally don't write that type of code. If you need different behaviors for the same method depending on certain variables, put it into different classes with the same interface. If you need to look up things based on a string, use an object instead. Input strings should always be transformed into some kind of object representation as early as possible. Chances are, at some early point you actually know exactly what type of object you need, but by moving the decision further down the chain by only passing along the string version of the input, you distribute the differences in behavior through the whole system instead of encapsulating them in one object. Then you end up with large if/else or switch blocks spread everywhere. More on reddit.com
03:09
Stop Using Switch in JavaScript - Use objects instead - YouTube
STOP Using Switch Statements! Use These Instead...
02:08
JavaScript Tip: Replace Switch Statements With Object Literals ...
08:10
STOP Using Switch Statements! Use These Instead... - YouTube
02:29
Stop Using If Else And Switch Statement in Javascript Except do ...
09:04
JavaScript Switch Case Statements - YouTube
W3Schools
w3schools.com › js › js_switch.asp
JavaScript Switch Statement
The switch ends (breaks) there anyway. The break keyword is crucial for preventing a "fall-through." Without break, the code will continue to execute the next case blocks (and the default block if present) even if their values do not match the expression. The default keyword specifies a block of code to run if there is no case match.
Ultimate Courses
ultimatecourses.com › blog › deprecating-the-switch-statement-for-object-literals
Replacing switch statements with Object literals - Ultimate Courses
July 17, 2014 - Objects are really flexible, they’re at the heart of pretty much everything in JavaScript, and using them instead of the switch statement has been something I’ve been doing lately. ... If you’ve not used switch before or are a little unsure what it does, let’s walk through it. What switch does is take input and provide an output, such as code being run. ... var type = 'coke'; var drink; switch(type) { case 'coke': drink = 'Coke'; break; case 'pepsi': drink = 'Pepsi'; break; default: drink = 'Unknown drink!'; } console.log(drink); // 'Coke'
Educative
educative.io › answers › how-to-convert-switch-case-to-objects-in-javascript
How to convert switch-case to objects in JavaScript
In JavaScript, we use the switch case in a place where we need to handle multiple if...else if...else if... statements. For example: ... Define the default property in the object and check if the case label is found in the object.
GeeksforGeeks
geeksforgeeks.org › javascript › switch-case-in-javascript
JavaScript switch Statement - GeeksforGeeks
May 19, 2026 - Default: Runs if no cases match. It’s optional but provides a fallback option. ... let day = 3; let dayName; switch (day) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; case 6: dayName = "Saturday"; break; case 7: dayName = "Sunday"; break; default: dayName = "Invalid day"; } console.log(dayName);
30 Seconds of Code
30secondsofcode.org › home › javascript › object › switch with object literals
Replacing JavaScript switch statement with object literals - 30 seconds of code
November 7, 2021 - Finally, our object literal replacement should be able to handle falling through cases, similar to what happens when there's no break statement. This is a matter of simply extracting and reusing logic in the object literal. let fruit = 'oranges'; switch (fruit) { case 'apples': case 'oranges': console.log('Known fruit'); break; default: console.log('Unknown fruit'); } // Logs: 'Known fruit' const knownFruit = () => console.log('Known fruit'); const unknownFruit = () => console.log('Unknown fruit'); const logFruit = { 'apples': knownFruit, 'oranges': knownFruit, 'default': unknownFruit }; (logFruit[fruit] || logFruit['default'])(); // Logs: 'Known fruit'
Enmascript
enmascript.com › articles › 2018 › 10 › 22 › why-i-prefer-objects-over-switch-statements
Why I prefer objects over switch statements
October 22, 2018 - The switch statement executes the block inside the second and third case even though the first case was already the correct one, it then finds the break keyword in the third case block and stops the execution, no warnings or errors in the console to let you know about it, this is the desired ...
SitePoint
sitepoint.com › javascript
Switch case with an object - JavaScript - SitePoint Forums | Web Development & Design Community
September 10, 2012 - Hi All, I need some help with JS which is a part of a sigma grid ajax function. Here’s an array with variable names as MySql table column names : var dsOption= { fields :[ {name : 'username' }, {name : 'full_name' }, {name : 'userlevel' }, {name : 'email' }, {name : 'phone' } ], recordType : 'object' } The field ‘userlevel’ can be 1, 5 or 9 and I don’t want to display numbers but strings like ‘guest’, ‘member’ and ‘admin’ respectively.
DEV Community
dev.to › lukyhenson › replace-your-switch-statement-and-multiple-if-and-else-using-object-literals-en-us-1dec
Replace your switch statement and multiple "if and else", using Object Literals - [en-US]. - DEV Community
November 28, 2019 - There are multiple issues with switch, from its procedural control flow to the non-standard-looking way it handles code blocks, the rest of JavaScript uses curly braces yet switch does not. Syntactically, it's not one of JavaScript's best, nor is its design. We're forced to manually add break; statements within each case, which can lead to difficult debugging and nested errors further down the case should we forget! We have to treat this with caution. We often use Object lookups for things in JavaScript, often for things, we would never contemplate using switch for - so why not use an Object literal to replace the switch?
Mastering JS
masteringjs.io › tutorials › fundamentals › switch-case
The Switch/Case Statement in JavaScript - Mastering JS
January 13, 2020 - const hero = 'Batman'; let sidekick; switch (hero) { case 'Batman': sidekick = 'Robin'; // Unless there's a `break`, JavaScript will execute the next // `case` block.
LogRocket
blog.logrocket.com › home › a practical guide to switch statements in javascript
A practical guide to switch statements in JavaScript - LogRocket Blog
February 26, 2025 - Object literals or even a series of if...else statements might be more appropriate. The default case is your safety net. It ensures that your code handles unexpected values gracefully. Always include a default case, even if it’s just to log an error message. The switch case in JS is a valuable addition to your JavaScript toolkit, offering a streamlined and organized way to handle multiple conditions.
JavaScript in Plain English
javascript.plainenglish.io › javascript-switch-case-vs-object-literal-e96c8fefa30f
JavaScript switch case vs object literal | by Pravin M | JavaScript in Plain English
October 24, 2024 - let day = 'Monday'; switch(day) { case 'Monday': console.log("Start of the week!"); break; case 'Wednesday': console.log("Mid-week."); break; case 'Friday': console.log("Almost the weekend!"); break; default: console.log("It's just another day."); } ... New JavaScript and Web Development content every day.
Jscrambler
jscrambler.com › blog › switch-statements-vs-object
Switch Statements vs Object: A Comparative Analysis
Code Duplication: If multiple cases require similar or identical code, there can be some code duplication within a switch statement. This can impact maintainability and increase the likelihood of errors. In JavaScript, an object is a complex data type that allows you to store and organize data using key-value pairs.
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript switch case
JavaScript switch case Statement
November 15, 2024 - Let’s take some examples of using the JavaScript switch statement. The following example uses the switch statement to get the day of the week based on a day number: let day = 3; let dayName; switch (day) { case 1: dayName = 'Sunday'; break; case 2: dayName = 'Monday'; break; case 3: dayName = 'Tuesday'; break; case 4: dayName = 'Wednesday'; break; case 5: dayName = 'Thursday'; break; case 6: dayName = 'Friday'; break; case 7: dayName = 'Saturday'; break; default: dayName = 'Invalid day'; } console.log(dayName); // TuesdayCode language: JavaScript (javascript)
TutorialsPoint
tutorialspoint.com › javascript › javascript_switch_case.htm
JavaScript - Switch Case
The JavaScript switch case is a conditional statement is used to execute different blocks of code depending on the value of an expression. The expression is evaluated, and if it matches the value of one of the case labels, the code block associated ...
YouTube
youtube.com › watch
Stop Using Switch in JavaScript - Use objects instead - YouTube
If you're still using switch case statements in JavaScript, you might want to start using objects instead. Using objects will result in less code and your co...
Published September 24, 2021