JavaScript Switch Statement Masterclass

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript Switch Statement Masterclass

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Basics

function logPrice(fruit) {
switch (fruit) {
case 'apple':
console.log('1.00');
break;
case 'banana':
console.log('0.50');
break;
case 'orange':
console.log('0.75');
break;
}
}

logPrice('apple'); // 1.00
logPrice('banana'); // 0.50
logPrice('orange'); // 0.75

Fallthrough

/** @type {200|300|400|500} */
let statusCode = 200;

switch (statusCode) {
case 200:
console.log('Success');
break;

case 300:
case 400:
case 500:
console.log('Error');
break;
}

default

function sendToArk(animal) {
switch (animal) {
case 'dog':
case 'cat':
console.log('lower deck');
break;

case 'chicken':
case 'pigeon':
console.log('upper deck');
break;

default:
console.log('extinct');
}
}

sendToArk('cat'); // lower deck
sendToArk('chicken'); // upper deck

sendToArk('dinosaur'); // extinct

Equality

// background on object equality
console.log('monday' === 'monday'); // true
console.log(1 === 1); // true
console.log({ name: 'John' } === { name: 'John' }); // false

// examples with switch
let person = {
name: 'John',
};
switch (person) {
case { name: 'John' }: // false
console.log('Hi John! -- will not work');
break;
}
switch (person.name) { // true
case 'John':
console.log('Hi John!');
break;
}

switch function return

function tossResult(value) {
//p
switch (value) {
case 0:
return 'Head';
case 1:
return 'Tail';
}
}

console.log(tossResult(0)); // 'Head'
console.log(tossResult(1)); // 'Tail'

block scope

const action = 'say_hello';

switch (action) {
case 'say_hello': {
let message = 'hello';
console.log(message);
break;
}
case 'say_hi': {
let message = 'hi';
console.log(message);
break;
}
default: {
console.log('Invalid action received.');
}
}

Object Lookup Pattern

Switch vs. Object Lookup:

function officeHours(day) {
switch (day) {
case 'Monday':
return '9:00 - 17:00';
case 'Tuesday':
return '10:00 - 17:00';
case 'Wednesday':
return '11:00 - 17:00';
case 'Thursday':
return '11:00 - 16:00';
case 'Friday':
return '11:00 - 15:00';
default:
return 'Closed';
}
}

console.log(officeHours('Thursday')); // 11:00 - 16:00
console.log(officeHours('Sunday')); // Closed

function officeHours(day) {
return ({
Monday: '9:00 - 17:00',
Tuesday: '10:00 - 17:00',
Wednesday: '11:00 - 17:00',
Thursday: '11:00 - 16:00',
Friday: '11:00 - 15:00',
})[day] ?? 'Closed';
}

console.log(officeHours('Thursday')); // 11:00 - 16:00
console.log(officeHours('Sunday')); // Closed
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

Switch statements is something that you can use to execute different actions or cases based on the value of a single JavaScript expression. Consider the simple example where we want to log the price of a fruit. We can easily do that using a switch statement and add its code. The switch statement consists of the switch keyboard followed by an expression that will be used to match against the different case clauses. As an example, if the fruit evaluates to the string apple, we want to log out 1.00. The case clause consists of the case keyword followed by the match value, followed by the colon, followed by the statements that you want to execute.

00:35

For this particular case, we can add as many cases as we need. For example, let's add a case for a banana and an orange, both with their own console log statements that log their individual prices. One very important fact to remember is that we almost always add a break statement at the end of individual case clauses, and this ensures that once that particular case is done, we break out of the switch statement, otherwise it would actually fall through to the next one. As an example, if you forget this particular break in apple after logging out 1.00, it would actually jump into the banana section and log out a 0.50.

01:13

But because we have the breaks in place, apple only logs out 1.0. Banana logs out 0 1 5 0, and there is no fall through between the different case statements. Sometimes you want to execute the same set of code for different values of the conditional switch expression, and for that we can use the fall through pattern. Consider the simple example where we have an H T P status code. That can only be the numbers 200, 300, 400 or 500. For the status code 200, we want to log out the string success and for all of the other codes, 300, 400, 500,

01:46

we want to execute the same code that logs out the string error. Instead of repeating this code block in the individual case statements, we can simply write the case statements and let them fall through by making sure that there is no break between the individual cases. As an example, if the status code is equal to the number 300, it's going to start executing any of the code that follows till it eventually hits the break statement and therefore it will execute this console log error. Adding an optional default clause to your switch statement allows you to handle unexpected values that do not match any of your case clauses.

02:22

Consider the simple example We we are sending the animal to the arc and placing them properly. For example, if the animal is a cat or a dog, we want to put them on the lower deck. If they are a chicken or a pigeon, we want to put them on the upper deck. And finally, for everything else, we want to make them extinct. If you want to capture anything that didn't match any case statement, we can do that with the default clause. And syntax wise, it is very similar to the case statement. It simply consists of the default keyword followed by a colon, followed by the code that we want to execute.

02:54

So now if you run this sent to arc function, a dog would go to the lower deck, a chicken would go to the upper deck and any other value, for example, the string dinosaur will fall through to the default clause and we will log out extinct. Internally, the JavaScript switch statement uses strict equality to compare the conditional expression with the individual case clauses. You can recall that JavaScript strict equality works perfectly fine for primitives like strings or numbers. So Monday is equal to Monday and one is equal to one. However, that is not true for objects.

03:26

So just because two objects are structurally equivalent, unless they are the same reference, they are not going to be strictly equal. With this recap out of the way, considered the simple object person that consists of a name property pointing to the string, John. Now we can be a bit crazy and try to use this object as is in a true statement and say that, Hey, if this person matches an object, name of John a logout, hi John, but this is not going to work. This case is never going to match because the underlying strict equality triple equal is always going to be false.

03:59

The proper way to do this switch statement would be to identify some property that can be used with strict equality and still uniquely identifies the object for our simple case using person do name which is of type string, and using that for the case clauses will work perfectly fine. You can see that hi, John has executed, but hi John will not work is nowhere way to be found in the output. If the code in the switch is within a function and you are going to return from some case, then for obvious reasons you don't need to have a break statement. In that case, consider the example where we have a trust result value,

04:33

which can be zero or one, and we want to return the string version for these values. So if the value is going to be zero, we are going to return the string head. And if the value is one, we return the string tail. Now because the case clauses end in a return statement, there is no need for a break as the code in the switch statement will stop executing just like any other code in the function once we hit the return statement. So tossed result zero will return the string head to result, one will return the string tail and we can verify that from the program output. Let's talk about some of the best practices regarding switch statements.

05:08

And a big thing worth knowing is that case statements don't create a block scope and it's up to you to create them using parentheses. Consider a simple action string that can be say hello or say hi. And then based on the value of action, we want to create a message variable which will be hello or Hi and then log that message out. This code looks perfectly fine, but when we actually try to run it, it'll actually fail. And the reason why is that we are actually declaring the same variable twice within the same scope because there is only one block scope over here and that is dictated by the parentes of the switch statement.

05:44

Now the fix is quite simple. We can actually create a block scope whenever we want by simply using parentheses ourselves so we can wrap the case statement bodies with parentheses, and now they are all Isolated into their own individual block scopes, which means that the message variable created in the first case is completely isolated from the message variable declared in the second case. So now the code will execute without any issues because the action is say hello. The first case block will execute and we see the string hello, log to the console.

06:16

When the evaluated result of the switch statement is a simple expression, it is conventional to replace the switch statement with an object looker pattern to achieve the same result with fewer lines of code. Consider this function office R that takes a particular day string and then based on the value of that string returns of working hours for that day, we have values for all the days Monday to Friday. And then for everything else which are weekends, we return the string closed. So if you pass in the string Thursday, we get 11 to four, and if you pass in the string Sunday we get closed.

06:49

Note that our function body consists of a simple mapping of one string to another along with the potentially default value. A feature of surescript is that we can actually use simple objects to create a mapping from one string to another. So from Monday to Friday we can provide the string values and then we can fetch the desired value from this object by using an index lookup passing in the provided day. Now, if the provided day does not exist within this object, for example, Sunday does not exist, then the Jiao script on time will give us the value undefined, which of course we can now call less to a default value. For example, hey,

07:24

we are defaulting it to the string closed. So if you passing in the string Thursday, it's going to look up the value for the string, and of course it's going to be 11 to four and for everything that is not present, for example, passing in the string Sunday, we get back the default value of closed. So in summary, in the object lookup pattern on the left hand side, we have the case clauses. On the right hand side we have the case results. The conditional switch expression is used as the lookup, and now coalescing is used to provide the default result. The object lookup pattern is a more functional programming inspired expression based version of a switch statement. I hope you enjoyed this tutorial.

08:01

As always, thank you for joining me and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36