Stop Using Switch in JavaScript - Use objects instead

preview_player
Показать описание
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 code will be easier to follow.

🌎 Follow me here:
Рекомендации по теме
Комментарии
Автор

Readability wise your second method is definitely preferred. Final approach is a bit overkill.

thydevdom
Автор

and not to mention the speed benefit, as object access constant time as it is hashed

tejasn
Автор

I don't get it, what if the switch's parameter was a string instead? If I want to access a value by a numeric index I can just define an array. Thanks for your tips btw.

jarndev
Автор

Interesting approach, however, I have not been able to type this correctly in TypeScript. Do you have any ideas on how to do this?

coder_one
Автор

What if I want when days = 0 it runs a code and not necessarily return a value.

victorpimentel
Автор

Can you do one where the values in those objects are functions with logic?

AmitErandole
Автор

Thanks brooo, btw kindly zoom the code its kind of hard to readd hehe loveyou

BSITVinluanEner
Автор

Great tutorial, thanks for sharing. I think the function layer might be overkill though, as for some it might be simple enough just to do a key/value object lookup;

//Where # is the day key number, this will return the day name value of an object "days"
console.log(days[#]);

karlstenator
Автор

This is not so much a reason not to use switches as it is simply using the proper form for a known dataset. Everyone knows that the Date() functions representation of days is a integer between 0-7, so the function needs to simply catch an error for any value other than [0-7] and then return the correct element from the days array/object (preferably embedded in the function, unless you code shares the array with another section of code). Now, reverse the process and determine which Date() day integer is associated to a given Weekday Name and explain if a switch or loop is the faster better code form.

MichaelKlineJr
Автор

Okay but what about multiple variables?

soundrogue
Автор

I already implemented my hash table before but this curry in js blows my mind

nikolam-dev