Learn Switch Statements In 7 Minutes

  Рет қаралды 42,622

Web Dev Simplified

Web Dev Simplified

Күн бұрын

JavaScript Simplified Course: javascriptsimplified.com
The switch statement is a really underutilized syntax that can drastically clean up specific long if else statements by making them easier to read and use.
📚 Materials/References:
JavaScript Simplified Course: javascriptsimplified.com
JavaScript Scope Video: • Learn JavaScript Scopi...
JavaScript Scope Article: blog.webdevsimplified.com/202...
🌎 Find Me Here:
My Blog: blog.webdevsimplified.com
My Courses: courses.webdevsimplified.com
Patreon: / webdevsimplified
Twitter: / devsimplified
Discord: / discord
GitHub: github.com/WebDevSimplified
CodePen: codepen.io/WebDevSimplified
⏱️ Timestamps:
00:00 - Introduction
00:30 - Code Demo
01:08 - Switch Statement Basics
04:45 - Matching Multiple Cases
05:59 - Common Mistakes
#SwitchStatement #WDS #JavaScript

Пікірлер: 83
@elokthewizard
@elokthewizard 8 ай бұрын
thanks! this helped me realize a switch block was NOT the correct way to handle what i was doing 😂
@rpf23543
@rpf23543 Жыл бұрын
your teaching style is so great, thank you very much!
@huge_letters
@huge_letters Жыл бұрын
tbh using Objects/Maps instead of switch usually is much more readable and convenient. You can use ?? to implement defaults, some prototype key collision(like valueOf) is not an issue 99% of the time(and can be avoided with null prototype or Map), having multiple values match the same case can also be fixed with Map. You can't really implement a case without a break tho unless you get really verbose but then just actually use a switch - but honestly how often do you even need this in a switch statement? If anything it makes your code even less readable when you have to consider that some cases don't cause a break. using switch over if else doesn't bring any benefits really - I find them both to be quite unreadable and verbose and I think performance-wise they're literally the same.
@JokeryEU
@JokeryEU Жыл бұрын
never used switch statements in a real project saw no reason too. best to not have so many if/switch statements in the first place
@snake1625b
@snake1625b Жыл бұрын
Yeah maps are way better, way less lines of code
@pranavbhat29
@pranavbhat29 Жыл бұрын
Kyle, what is your opinion on use of switch statements versus objects with keys being the case constants and values being the case blocks wrapped in functions? Of course readability will take a hit, but will that not make the code more declarative and hence reactive?
@AmaniTinbite
@AmaniTinbite 9 күн бұрын
Your videos are so easy to understand thanks Bro👌👌
@sixira678brawl
@sixira678brawl 4 ай бұрын
Thank you so much, you explain magnificantly
@BryanGranseDevs
@BryanGranseDevs 8 ай бұрын
Never tired watching and executing your tutorial ❤
@torbenwranglaursen6654
@torbenwranglaursen6654 Жыл бұрын
In php I sometimes do this: switch(true) { case ($myVar1 < 5): {echo "case 2 " ;break;} case ($myVar2 != "foo" ): {echo "bar" ;break;} case ($myVar3+2 < 5): {echo "foo bar" ;break;} }
@krlst.5977
@krlst.5977 Жыл бұрын
You can also do the same in the JS since CASE checks for TRUE, btw Kyle should've been mentioned this also that CASE has STRICT comparison. So once you put some datatype in the switch's parentheses the same type of data expected in the CASE.
@futureferrarimusic
@futureferrarimusic Жыл бұрын
Thanks WDS!
@erfanvatanparasti2949
@erfanvatanparasti2949 Жыл бұрын
Your videos are the best in KZfaq. But this one was simple and trivial. By the way, Thank you
@aronagueye9151
@aronagueye9151 Жыл бұрын
great video 👍🏿
@Spunky_Tx
@Spunky_Tx 24 күн бұрын
Thank you
@rossclutterbuck1060
@rossclutterbuck1060 Жыл бұрын
But you can use switch statements to check if, say, a number is less than 5. You just need to gently abuse what a switch is used for. The expression in a switch statement is the value you are testing your cases against, and if the derived value of the case matches the derived value of the expression then a Boolean true happens which runs the code inside the matching case. So, you can shortcut a switch by setting the expression to be a Boolean true and then do whatever you want in the cases const x = 50; switch (true) { case x < 50: console.log("Less than 50"); break; case x > 50: console.log("Greater than 50"); break; case x === 50: console.log("Exactly 50"); break; default: console.log("x isn't a Number"); }
@Lernschau
@Lernschau Жыл бұрын
that's actually how I write many of my switch statements :D you can then also compare to function results; each case becaomes like a stripped down if statements
@rossclutterbuck1060
@rossclutterbuck1060 Жыл бұрын
@@Lernschau I rarely need and if...else these days, but when I do there's usually a couple of else ifs in there so I rewrite as a switch block like the above. However if I have a lot of conditions I actually iterate over an array of objects and return whatever matches my incoming condition first.
@MB-zj3er
@MB-zj3er Жыл бұрын
Is this abuse though? It follows the logic. I use it quite a bit.
@rossclutterbuck1060
@rossclutterbuck1060 Жыл бұрын
@@MB-zj3er abuse is probably too strong a word, but it's not strictly how a switch block is intended to be used. But using a Boolean as the expression is well documented at MDN, so it's not like it's a super bad thing.
@rishiraj2548
@rishiraj2548 Жыл бұрын
Thanks
@tabrezdn1
@tabrezdn1 Жыл бұрын
Thanks for always enlightening us!
@consig1iere294
@consig1iere294 Жыл бұрын
Kyle is super awesome at teaching stuff. That being said, I just don't see the need to get into Switch Statements unless there is a huge performance increase. It can't do anything else other than equals, needs breaks... whereas if/else is much easier for a newb like myself to understand and all Comparison Operators work with it. Can anyone please share the more advantages to Switch?
@MichaelKlineJr
@MichaelKlineJr 9 ай бұрын
Switch statements are operational sorters. Give it a list of objects or arrays with a noun key (type, make, model, gender, etc) that the statement is designed to sort through and perform a logical operation on. You can also encapsulate switch statements into functions and use functions, with switch statements in them, as case operations to create cascading sorting operations.
@funkenjoyer
@funkenjoyer Жыл бұрын
I generally don't like switch statements, they take a lot of space and look ugly af (thats personal preference tho), also the fact it does the fallover when you dont have break is an easy way to end up with a bug that's not very obvious (thats kinda depending on what type of logic is in there), what I tend to do instead is just use maps/objects (or whatever u call the equivalent in any given language) and just map the values straight to the logic that handles them
@LucasNovaes2023
@LucasNovaes2023 Жыл бұрын
Can you repeat this example using object literals instead?
@dsb5417
@dsb5417 10 ай бұрын
i love this channel
@Smurfis
@Smurfis Жыл бұрын
Hey bro, how are you changing multiple words at once for example you highlighted cat and changed it to bobcat twice
@noriller
@noriller Жыл бұрын
you can also drop the "break" if you add "return"
@knull9566
@knull9566 Жыл бұрын
Hey bro I had developed a simple react website it's running properly in firefox but lagging in chrome and other browser
@firedforfighting
@firedforfighting Жыл бұрын
I much rather a lookup table/dictionary but the problem is most people use object literal when they should be using map
@Zangief001
@Zangief001 Жыл бұрын
Great ad :))
@metalsadman
@metalsadman Жыл бұрын
how bout using object literal for simple cases like this one.
@soniablanche5672
@soniablanche5672 Жыл бұрын
you can put the default case first btw
@rubithalengai6817
@rubithalengai6817 9 ай бұрын
Hi, is there any way to change a=× b=y If(a=× and b=y){} to switch statement?
@Abrordev_Axmedov
@Abrordev_Axmedov 9 ай бұрын
I guess no
@tylerpestell
@tylerpestell Жыл бұрын
This is one instance I actually prefer VBs implementation where there is no need for a break statement. I can’t think of a single instance where I didn’t want the break in each case, so why not just make that the default behavior?
@darz6012
@darz6012 Жыл бұрын
because you can stack multiple cases on top of each other so that the same exact code will run for multiple different values.
@tylerpestell
@tylerpestell Жыл бұрын
@@darz6012 To me that is still an ugly implementation as you have to write “case” multiple times. In VB you can do the same thing you just have a list of values “cat”, “jaguar”, “bobcat” for one case. I don’t think I have ever had to use that though. I would go a different route at that point, as I think switch can get ugly quick if it gets too complex.
@nikita_suiazov
@nikita_suiazov Жыл бұрын
Switch case is antipattern. Better way is to use hash (object)
@daydreamer9469
@daydreamer9469 Жыл бұрын
Object or Map is better than switch statements in my opinion
@GregSinclair-gh3so
@GregSinclair-gh3so Жыл бұрын
if you want to use greater than, less than in your switch statement try this: switch (true) { case x < 5: console.log('small');break; case x >= 5 && x < 10: console.log('medium');break; case x >= 10: console.log('large');break;
@pppluronwrj
@pppluronwrj Жыл бұрын
looks worse than if else
@pppluronwrj
@pppluronwrj Жыл бұрын
id rather use json objects as map console.log(message[faveAnim] || "unheard")
@huge_letters
@huge_letters Жыл бұрын
JS has ?? as of recently which only "triggers" on undefined & null unlike || which triggers on all falsy values. So 0 ?? 5 => 0 but 0 || 5 => 5. Unfortunately it ignores NaN so NaN ?? 5 => NaN.
@pppluronwrj
@pppluronwrj Жыл бұрын
@@huge_letters in that case || is still better.
@techsamurai11
@techsamurai11 4 ай бұрын
Switch would be great if it behaved like Select Case without the breaks.
@harmez7
@harmez7 Жыл бұрын
dogs are actually awesome animals and they can be taught to not make loud sounds while being at home dont hate them Kyle
@georgebazerashvili9250
@georgebazerashvili9250 Жыл бұрын
Best youtuber
@bryson2662
@bryson2662 Жыл бұрын
I don't like switch statements. I really wish they were exhaustive or more like match statements in rust
@ESArnau
@ESArnau Жыл бұрын
I prefer if over switch.
@josephononaye7754
@josephononaye7754 10 ай бұрын
Thanks for the video. It was difficult following you because you talk fast
@artstrange3230
@artstrange3230 4 ай бұрын
Not adding a break;/return; statement after your logic is complete is a bad practice. You want the logic under a specific case to be executed and proceed with the rest of the code outside of the switch~case block. Always add a break; statement after you're done with your case logic. Additionally, I know this is JavaScript, but make sure to manipulate the input string into something generic, such as all lowercase to make sure user input won't be a problem. Where applicable, use Enums and other values you can directly control when using switch~case. Performance-wise, it's much better than an if~else if block. You should really be using if~else if when you have multiple mutually exclusive conditions that can be fulfilled within the same program loop (such as whether the user has admin rights and is logging on with certain options enabled). If it's a single variable that can contain multiple values you need to check for, switch~case is better.
@Shulkerkiste
@Shulkerkiste Жыл бұрын
For this case I use switch statements like this: function getAnswer(animal) { switch (animal) { case 'cat': return 'Cats are great' case 'dog': return 'Dogs are kinda loud' case 'shark': return 'That's an interesting choice' default: return 'I have never heard of that animal' } } I like to use oneliners in these kind of cases because every line belongs to a value. It's also easy to test because it's a pure function.
@danielnoyes
@danielnoyes 11 ай бұрын
only things i have against this video is how cats are better than dogs
@deatho0ne587
@deatho0ne587 Жыл бұрын
This is decent info to know how these work, but really should not be used anymore. Switches generally does not lead more maintainable/readable code. Heck there is proof with someone showing that you can write conditionals of less than and greater than.
@geoblk3000
@geoblk3000 Жыл бұрын
Some say, switch is an anti-pattern.
@josemonge4604
@josemonge4604 Жыл бұрын
It's not if it's implemented the right way, like in Rust for example, which forces you to explicitly declare all case and uses pattern matching.
@toshiracek2440
@toshiracek2440 Жыл бұрын
someone show this video to yanderedev
@EmmanuelOdii80
@EmmanuelOdii80 Жыл бұрын
First comment. That's Kyle
@SeanLinTw
@SeanLinTw Жыл бұрын
I don't like the switch syntax, usually i do this let favoriteAnimal = { "cat": ()=>{ console.log("Cats...")}, "dog": ()=>{ console.log("Dogs...")} } favoriteAnimal["jaguar"] = favoriteAnimal["cat"]; favoriteAnimal["jaguar"]();
@khoroshoigra8388
@khoroshoigra8388 Жыл бұрын
im doing this too sir
@dimitridoroshko
@dimitridoroshko Жыл бұрын
In my opinion, switch statements is bad style. It's hard to read and maintain
@Ray_Roele
@Ray_Roele Жыл бұрын
But scope wise, it much more optimise, especially when you need to use in function wich require multiple use, for example if using dice function and result of this function for future value. the only thing you can get lazy with writing breake, but common, cntrl+c cntrl+v, or even pretier special config set up done, tell me you point in details if its not hard?
@dimitridoroshko
@dimitridoroshko Жыл бұрын
@@Ray_Roele for example you might confuse another developer reading your code with purposefully leaving out a break statement when it's really needed.
@lovelytingy
@lovelytingy Жыл бұрын
@@dimitridoroshko then comment are come into play
@CrAzZyKiLleR01
@CrAzZyKiLleR01 Жыл бұрын
Absolutely disagree. In case you have certain ENUM values you can force yourself (via eslint) to handle each case. Adding another value the enum will automatically produce an error - perfect for you to known where you need to handle the new case.
@ToadyEN
@ToadyEN Жыл бұрын
I agree! I was taught to not put logic inside switches tens of years ago
@isaacbaptista6207
@isaacbaptista6207 Жыл бұрын
I still think switch statements are useless compared to ifs
@grgvgrgv
@grgvgrgv Жыл бұрын
swith-case is a bad programming practice.
@KnowledgeBoxMM
@KnowledgeBoxMM Жыл бұрын
I'm first comment...
@sfox-j
@sfox-j Жыл бұрын
your third comment
@Noam-Bahar
@Noam-Bahar Жыл бұрын
Objects are better: const favoriteAnimals = { cat: "Cats are great", dog: "Dogs are kinda loud", shark: "That's an interesting choice", } function getAnimal(animal) { const animalDescription = favoriteAnimals[animal] ?? "I've never heard of this animal"; // For beginners: read more about short if statements, short circuiting, and nullish coalescing. console.log(animalDescription); } If you want multiple animals to match the same result, such as Cat, Bobcat, and Jaguar all matching "Cats are great", you can use multiple techniques. If can get pretty verbose, and switch is bad imo. I used an array with the allowed values, and return "cat" if the animal exists in the array function getCat(animal) { const cats = ["jaguar", "bobcat", "cat"]; return cats.find(cat => cat === animal) ? "cat" : undefined; }
@gurvirbaraich2028
@gurvirbaraich2028 Жыл бұрын
Bro did you see my email.
@mjanta
@mjanta Жыл бұрын
or you can rewrite it to: const favoriteAnimal = "shark"; const favoriteAnimalList = { cat: () => console.log("Cats are great"), dog: () => console.log("Dogs are kinda loud"), shark: () => console.log("That's an interesting choice"), }; favoriteAnimalList[favoriteAnimal] ? favoriteAnimalList[favoriteAnimal]() : console.log("I have never heard of that animal");
@KURWAMACJAPIERD0LE
@KURWAMACJAPIERD0LE Жыл бұрын
Make youreself a favor and dont use switch at all. Its bad practice. There are other, more readable ways
How To Create/Use Functions - JavaScript Essentials
9:34
Web Dev Simplified
Рет қаралды 117 М.
why are switch statements so HECKIN fast?
11:03
Low Level Learning
Рет қаралды 390 М.
NERF WAR HEAVY: Drone Battle!
00:30
MacDannyGun
Рет қаралды 58 МЛН
Best father #shorts by Secret Vlog
00:18
Secret Vlog
Рет қаралды 22 МЛН
Scary Teacher 3D Nick Troll Squid Game in Brush Teeth White or Black Challenge #shorts
00:47
Этот Пёс Кое-Что Наделал 😳
00:31
Глеб Рандалайнен
Рет қаралды 4,5 МЛН
#23 How to use the Switch Statement | JavaScript Full Tutorial
10:55
Learn JavaScript Scoping In 10 Minutes
11:39
Web Dev Simplified
Рет қаралды 58 М.
Two Sum | LeetCode 1 | JavaScript | Easy
13:20
Gordon Zhu
Рет қаралды 8 М.
The Most Important Skill You Never Learned
34:56
Web Dev Simplified
Рет қаралды 176 М.
Speed Up Your React Apps With Code Splitting
16:50
Web Dev Simplified
Рет қаралды 372 М.
8 Must Know JavaScript Array Methods
10:05
Web Dev Simplified
Рет қаралды 1 МЛН
Switch Statements - Beau teaches JavaScript
3:20
freeCodeCamp.org
Рет қаралды 76 М.
Top 10 Advanced CSS Responsive Design Concepts You Should Know
20:16
Web Dev Simplified
Рет қаралды 508 М.
Top 6 React Hook Mistakes Beginners Make
21:18
Web Dev Simplified
Рет қаралды 563 М.
Fastest Way to Learn ANY Programming Language: 80-20 rule
8:24
Sahil & Sarra
Рет қаралды 784 М.
NERF WAR HEAVY: Drone Battle!
00:30
MacDannyGun
Рет қаралды 58 МЛН