Using Switch Statements Flashcards
What are Switch Statements?
They are used inlace of If/Else to write more efficient / condensed code.
What are the 4 parts to a switch statement?
Switch = tells JS that you're about to list conditions. Case = think of "incase". States the parameter, and then is followed by an alert. Break; = Prevents fall through ( code continuing through even after a parameter was met). Use it after every case Default = if user gives an undefined parameter, it is the catch all.
How do you start writing a switch?
if (grade === "regular") { alert("Its $3.35"); } BECOMES switch (grade) { case "regular":
How do you write a case?
if (grade === "Regular") { alert("Its $3.35"): } becomes switch (grade) { case "regular": alert("its $3.35"): break; case "premium": alert("its $4.50"): break; }
Do you use colons or semicolons after every case?
you use colons. :
Does break; go before or after alert() ?
after. you break your code after each alert you present.
Give an example of default:
break:
alert(“that is not valid grade”):
}
What punctuation do you use after each: break, case, switch, default
break; (semi)
case: (colon)
switch (var) {
default:
What is fall through?
Code automatically wants to go to the next line of code regardless if a condition is met. That is fall through. you prevent it with break;
Write a sample code for 3 types of fruit and make sure to have a default.
BONUS = Turn it into a function.
… You have fun with that one :D …