Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Shameel Uddin
Shameel Uddin

Posted on

     

JavaScript One-Liner To Replace Switch Statement 🚀

JavaScript is a cool language with many hacks available to traditional methods. There's an excellent way to replace switch statements by using objects!

Let's take a closer look at how you can make your JavaScript code cleaner and more readable by transitioning fromswitch statements to object-based alternatives.

Traditional way - Switch Statements

constgetAnimalName=(animalType)=>{switch(animalType){case'dog':return'🐶'case'cat':return'🐱'case'parrot':return'🐦';default:return'Unknown';}};
Enter fullscreen modeExit fullscreen mode

Usingswitch statements can sometimes lead to unwieldy and hard-to-follow code, especially as your project grows.

The Good Way: Object Literals

constanimalNames={'dog':'🐶','cat':'🐱','parrot':'🐦',};constgetAnimalName=(animalType)=>animalNames[animalType]||'Unknown';
Enter fullscreen modeExit fullscreen mode

Embrace the power of object literals! 🌟 By mapping values to their corresponding results in an object, you can make your code more elegant, clean, and easier to maintain.

The Benefits 🌈

👉Readability: Object literals make your code more straightforward to read and understand. You can quickly grasp what each value represents.

👉Maintainability: When you need to add or modify mappings, you only need to update the object, keeping your codebase organized and maintainable.

👉Reduced Errors: Object literals reduce the chances of making typos or forgetting abreak statement, which are common pitfalls inswitch statements.

👉Cleaner Code: Cleaner code is not just a buzzword; it's a reality when you use object literals. Your code becomes more concise and easier to work with.

Happy coding! 🎉💻✨

Follow me for more such content:
LinkedIn:https://www.linkedin.com/in/shameeluddin/
Github:https://github.com/Shameel123

Top comments(14)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
tylim88 profile image
Acid Coder
Who needs meth when you have Typescript?
  • Joined

switch: faster

object: cleaner but consume more memory

CollapseExpand
 
artydev profile image
artydev
  • Joined
• Edited on• Edited

For the pleasure only :-)

Play with it here :animals

constanimalNames={'dog':'🐶','cat':'🐱','parrot':'🐦',};consthandler={get:(_,animalType)=>{return`<div style='font-size:3rem'>${animalNames[animalType]}</div>`||'Unknown';}}constanimals=newProxy({},handler)const{dog,cat,parrot}=animalsdocument.body.innerHTML=`  <div>This is a${dog}</div>  <div>This is a${cat}</div>  <div>This is a${parrot}</div>`
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
grunk profile image
Olivier
French full stack lead dev. Playing with stuff like PHP, emberjs, C++, Java, ...
  • Work
    Lead Dev
  • Joined

I'm sorry but at which point a "trick" is an improvement in readability compared to a statement known by any developer in almost all language ?

In my opinion any one liner is usually hurting readability compared to more verbose equivalent because you usually need to stop to understand what's happening in this succession of command

CollapseExpand
 
artydev profile image
artydev
  • Joined
• Edited on• Edited

@olivier
I don't think this is a 'trick", this is at least for me, a real feature.
You are absoutely free to use it or not, but everyone should be advertised of those little kown features

Regards

CollapseExpand
 
shameel profile image
Shameel Uddin
Tech Enthusiast, eager to learn latest trends of digital world!
  • Education
    Masters in Computer and Information Engineering
  • Work
    Software Engineer
  • Joined

This is not anall-developer thing. If you are into JS then you learn these kind of things to increase readability.

More verbose does not always been better readability, as most people have started to brag about after taking a reverse-brake these days.

CollapseExpand
 
frankwisniewski profile image
Frank Wisniewski
programmer specializing in:Javascript, PHP, assembler
  • Location
    Adenau
  • Joined
• Edited on• Edited

I wouldn't think of using the switch statement for this use case.

The example is misleading in that the function getAnimalName doesn't return an animal name but the corresponding symbol for the animal. It should, therefore, be correctly named getAnimalSymbol.

There is no need to write a function for this.

const animalsymbols = {    'dog': '🐶',    'cat': '🐱',    'parrot': '🐦',  };  console.log(    animalsymbols['dog']??'�'  )
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
shameel profile image
Shameel Uddin
Tech Enthusiast, eager to learn latest trends of digital world!
  • Education
    Masters in Computer and Information Engineering
  • Work
    Software Engineer
  • Joined

Seems more like a variable name change, not an entire use-case change from this example.

CollapseExpand
 
efpage profile image
Eckehard
Always curious...
  • Location
    Germany
  • Work
    Numerical simulation specialist, IoT developer
  • Joined
• Edited on• Edited

The switch statement in Javascript is pretty verbose, so this is a nice inspiration to think about better solutions.

Switch is usually used with "break", so the code tends to be pretty verbose. But it is able to handle different code in each statement, so anobject literal selection is no substitute for switch !!!

Here is a typical - but not very useful - example, just to showcase some options

functionmakeSound(animalType)=>{leta=0switch(animalType){case'dog':alert("bark")a=1breakcase'cat':alert("meuw")breakcase'parrot':alert("make America great again")breakdefault:a=-1}returna};
Enter fullscreen modeExit fullscreen mode

So, what can we do here to make things better?

Solution A: Better formatting

functionmakeSound(animalType)=>{leta=0switch(animalType){case'dog':alert("bark");a=1;breakcase'cat':alert("meuw");breakcase'parrot':alert("make America great again");breakdefault:a=-1}returna};
Enter fullscreen modeExit fullscreen mode

Solution B: Use else If

functionmakeSound(animalType)=>{leta=0,N=animalTypeif(N=='dog'){alert("bark");a=1;}elseif(N=='cat'){alert("meuw");}elseif(N=='parrot'){alert("make America great again");}elsea=-1}returna};
Enter fullscreen modeExit fullscreen mode

Solution C: Use object literal with arrow functions

functionmakeSound(animalType){leta=0constfn={dog:()=>{alert("bark");a=1},cat:()=>{alert("meuw");},parrot:()=>{alert("make America great again")}}letf=fn[animalType]if(f)f()elsea=-1returna};makeSound("dog")
Enter fullscreen modeExit fullscreen mode

If you do not need to handle the "default" case, this is much better readable:

functionmakeSound(animalType){leta=0constfn={dog:()=>{alert("bark");a=1},cat:()=>{alert("meuw");},parrot:()=>{alert("make America great again")}}fn[animalType]()returna}makeSound("dog")
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
citronbrick profile image
CitronBrick
Developper
  • Work
    Junior Front End Engineer
  • Joined

This seems to be the standard in Python, as it does not have aswitch statement.

CollapseExpand
 
azkaar_rauf profile image
Azkaar Khatib
  • Joined

You usematch instead ofswitch in python

CollapseExpand
 
citronbrick profile image
CitronBrick
Developper
  • Work
    Junior Front End Engineer
  • Joined
• Edited on• Edited

Thank you. It's the 1st time I'm hearing aboutmatch.

Thread Thread
 
azkaar_rauf profile image
Azkaar Khatib
  • Joined

Anytime 😊

CollapseExpand
 
bwca profile image
Volodymyr Yepishev
I like coding :)
  • Education
    Kyiv National Linguistic University
  • Work
    Application Developer
  • Joined

Let's add another case, chihuahua, which requires you to use the dog emoji, as in the dog case, how would you tackle this with object?

CollapseExpand
 
sherzodaxadov profile image
Sherzod Axadov
  • Joined

very good solution bro👏

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Tech Enthusiast, eager to learn latest trends of digital world!
  • Education
    Masters in Computer and Information Engineering
  • Work
    Software Engineer
  • Joined

More fromShameel Uddin

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp