Javascript; The Case for the Switch Statement

Nick Galante
6 min readNov 12, 2020

--

Photo by Yassine Khalfalli on Unsplash

Cool switches above right? Alright so, typically I take to Medium to write tutorials or rapid explanations of some specific coding facet such as navigation, filtering, blah, blah, blah. Those are a great read if you’re just getting into coding, and you want to establish some quick ‘best practices’ to getting your project off the ground.

As of recently though, I have been hired out to develop a UI for an ML-driven psychological typing application, and it’s afforded me the opportunity to try out some newer ways of applying the same old principles that I have loved since I began coding. Today we’re going to talk about an application of the Switch/Case statement in Javascript, and how we can use it for dynamic content rendering in React.js. Super cool, lots of fun, let’s dive in.

Ok, so I think the thing that most people forget when working with React is that it’s simply a Javascript library; it’s not its own framework with its own unruly syntax and structure, and apart from the JSX returned by components, it’s really just a very powerful, holistic representation of the extents to which you can use Javascript; and in that React is just a specific structure and sandbox for the streamlined development of web apps with Javascript, you can really help yourself get the most out of React by getting the most out of Javascript. Now let’s talk about the Switch/Case statement.

So, the Switch/Case statement is something that you are probably most familiar with if you frequently use Redux in your projects, because the Reducer logic is constructed with the help of Switch/Case statements. But if you’re not that familiar yet, don’t beat yourself up really. This is where you learn. So Switch/Case has its largest part in areas that necessitate conditional rendering. Sounded like a textbook definition right there, so let’s just say it is a way to structure if conditional statements in a more efficient way, if you are working within the confines of a strict range of values. You know what? I’ll just show you;

The traditional conditional statement, used with the if statement, executes a block of code, if the conditional parameter fed to the if statement evaluates to the Boolean value true. That’s a lot of code jargon, and I’m willing to bet you already know how if statements work. But as a template, they run something like this:

yup

However, let’s say that you wanted to write a function that runs through an array of your friends’ names, and prints a custom ‘hello’ message to them. Well if we were to structure this with if statements, that may result in a lot of code at the end of the day. You’d have to write else if statements for each name in the array so that you could dynamically print each of the names, while iterating through that friends array. Like this:

And that just looks really tedious, going through every single conditional statement and making sure the values match up just right. This looks like a CASE for the SWITCH statement, which excels at executing blocks of code according to matching arguments. See what I did there? If we were to organize this code to perform the same task, but with a switch statement, we would have much more readable, deliberate, and purposeful code. Watch:

The switch takes the argument its fed, a specific friend, and runs through all the various cases we’ve defined until it reaches an exact match, and then executes this block of code. It accomplishes the exact same task, and yet it’s more direct, meaningful, and explicit code that would help a fellow developer joining the project be able to make a quick inference about the intention of the function. And as a developer, that right there should be your goal. There are about 4 million ways to accomplish the above task, and dynamically print names, but in this manner, the intention is explicit, the code is deliberate and succinct, and we’ve stripped away a lot of the verbosity that accompanies nesting if statements and else if statements. If you’re unfamiliar with the keyword break it functions similar to a return statement, in that the code being executed will stop at the break and exit the function, you know like a BREAK-point.

OK Cool Nick, you explained how to use switch/case statements, but like how did you use it in React, and why should I even care?

You’re asking the right questions. Ok so remember when I said that React was a Javascript library and not a framework, and that makes a rather large difference? I’m happy you took my word for it, because it does. So let me get you up to speed. For this project I’m working on, there is a need for a lot of conditional content, based on the user’s progression through the app. Which means for one specific section of the app, the content is consistently changing to reflect the current question the user is on. Oh no. Did you hear that? Sounds like a case of dynamic content that a switch statement would be perfect for. So here is how I broke it down. First, i opened up two variables, with no real value, using the let javascript keyword, content being assigned a null value, and the current question having no value.

Then with the help of the React hook useState, I initialized a starting point for the component, starting the question order at the first question, i.e. 1.

Then I devised a way to use this currentQuestionOrder state, and map through the array of all questions to isolate only the Question Object that the user was currently on.

We then finally assign thisQuestion a value, assigning it to the returned value from the function findThisQuestion;

Now, thisQuestion has a value equal to the Question Object that the user is currently on. What I was able to do then, was create a function that would take in the Question Object as an argument, and use it’s specific attributes to populate the page content. Interpolating thisQuestion’s specific attribute values into prewritten JSX components, or in this case React Native components (the app I’m demonstrating with is a React Native App that uses Views, Texts, etc as opposed to traditional HTML and CSS, like on the web).

Then, in the return statement of the component, we simply wrap up the variable content in brackets so React knows to execute that code as javascript, and since that javascript function returns JSX or Native code, the engine your using whether it be a browser, or native platform, is able to run the code and return to you that new dynamic content.

When a user selects an answer, we raise the question order by one. Which changes the state of the app, triggering a rerender, meaning that content will now display entirely new attributes specific to the next question the user is on, and so on and so forth. Just another way to go back and refactor your app to be a bit more direct and purposeful with how our code is structured.

--

--

Nick Galante

Senior Software Engineer @ Charter Communications, Previously @ Amazon Games, Amazon Prime Gaming