Stop Using Switch in JavaScript - Use objects instead

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
if you're still using switch case statements and you watch this video to the end i hope you change your mind and stop using them so you can see here that we have a switch case statement that is going to get the day number and then we're going to declare day and then we're going to run through a list of days and we're going to reassign day and finally we're going to return the day so if we run this code here node1.js we get monday because the day is the first day of the week so how can we refactor this to make it a little bit nicer so a popular way to refactor switch case statements is to use an object so let's define const days equals we're going to create a new object and i'm going to say the 0th day is sunday the first day is monday 2nd is tuesday third is wednesday 4th is tuesday and so on so now that we have the day number we can simply return days and put the day number in as the item that we want to pick out of the object so let's remove all of this code here and you can see that we've already dramatically reduced our switch case statement let's run this again and we get monday but what happens if we want to add a default property here so we can say this is equal to 8 or new date and you can see that we get undefined so let's simply say days day number or let's return wtf and you can see we get wtf so this can still be a little bit messy let's abstract the switch case logic out into a function and so we can reuse it over and over again i'm going to say const which case is equal to and this is going to take an object and so the object that it's going to take is going to be these days and it's going to take a default value and we're just going to default that to default so this is going to be a curried function so we can say it to a carried function and the second parameter it's going to take is value and then we just want to return object we want to pick out the value or we want to return our default value so how would you use this switch case function let's declare our days again and we need to make a function from switch case so let's say const get day equals switch case and we can pass in our days now we just need to call get day and we can call it with all of our arguments so let's run node3.js and you can see here that it prints out all the days of the week so this is a fantastic alternative to switch case it's much neater and much easier to read thank you for watching and i'll see you in the next video
Info
Channel: TomDoesTech
Views: 425
Rating: 5 out of 5
Keywords: javascript, clean code, switch case, switch javascript, switch case javascript
Id: 3GJ0Q9EEKJk
Channel Id: undefined
Length: 3min 9sec (189 seconds)
Published: Fri Sep 24 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.