What are control structures in javascript?
Show
There are many ways to direct the way your code flows in a program, but first let’s define what control structures are in simple terms. Control structures in programming allows you as a developer to execute(or make decisions on) certain statements or expressions of code. In a way, it’s like hiking up a mountain and stumbling upon a fork in the road where one path takes you back to the base and the other to the summit. It’s also a way for you as a developer to make decisions to proceed with a statement when certain conditions are met or not. Choices. Choices. Choices. In JavaScript, there are many ways to leverage built-in control structues to control the flow of your code. Here are a few we are going to look at today:
The purpose of this article is to introduce the reader to different ways that you can control the way your code flows. This is by no means a comparison or use this vs. that type of article. For the sake of simplicity, I avoided including any looping mechanism as part of this list, I may have also forgotten one or two additional control structures. BUT. Let’s get started! If/Else StatementsAn if or if-else statment is a conditional statement that allows us to execute a block of code if a specified condition is truthy. If it is falsy then another statement is executed. This is one of the simplest conditional statement you will learn for any language. Below is the syntax of a simple if statement. Syntax if ( condition/conditions ) { This could be visually represented as follows: Pic from Eloquent JSAs an example, here is a simple if statement that checks whether a number is even and prints TRUE or FALSE. In the above example, we observe that the condition checks if the number is divisible by 2 with the modulo operator. The
modulo operator returns the remainder of a value. The Let’s look at a slightly more complex example with the classic fizzbuzz problem. If you are unfamiliar with fizzbuzz please see the wiki link here. The gist of the problem is as follows:
Visually, this could be represented as follows: The fizzBuzz example demonstrates a slightly more complex if/else statement with multiple conditions. This example also highlights the importance of condition placements. In general, stricter conditions are placed at the top to ensure that the flow does not default to less strict conditions Switch StatementsPic from GoogleSimilar to how an if statement works, a switch statement will also evaulate a condition(expression), once an expression matches to a case clause, the construct will execute statements associated with that case clause. Syntaxswitch (expression) { The expression shown in the above syntax will be compared and matched with each of the clauses until it either finds a match or reaches the default where it cannot find a match. The ExamplesA simple example of Here is another example evaluating a few HTTP codes, handling client error responses(4XX): The above is a fairly simple usage of a Lookup TablesPic from GoogleLookup tables, Hash Maps, or Maps. These are a few terms used today to describe another type of data structure which we can use to control data flow combined with nullish coalescing operators in JavaScript. Please note, there are distinctions between hash maps, objects, and maps, but our focus is to see how we can leverage this to control our code. To make this work, we will need to create a lookup table and use nullish coalescing operator(??) to handle the evaluation for us. The idea of a lookup table is akin to searching for a word in the dictionary and then return the definition of that word once it is found. Please see the following documentation from MDN to learn more about nullish coalescing operator. Syntax// Object The way nullish coalescing operator works is that it will return the value of the left-hand side of We will look at two distinct approaches to creating a lookup table:
Lookup Table with JavaScript ObjectLet’s take a look at lookup table using objects in JavaScript. Recall in the switch statement section there was an example looking at different client response codes (4XX errors) to be specific. // Switch Statement: Client Response Codes Let’s take this and throw each clause/statements into an object as a property. Next, create a function called The way the above example works is that it will pass in the statusCode as a key to search for in the clientResponseCode table. If the term is found, then it will return it’s left-hand side operand Lookup Table with JavaScript MapInstead of using a JavaScript The syntax to instantiate a Map data structure is as follows: // Map Let’s take that JavaScript Object from the previous clientStatusCode table and convert it into a map: After we create this Map let’s see how we can utilize nullish coalescing operator. const getHttpStatusCode = statusCode => clientResponseCodeMap.get(statusCode) ?? clientResponseCodeMap.get(500); The approach is similar to using nullish coalescing operators for an Ternary(Conditional) OperatorsTernary operators is typically used as an alternative to an if/else statement. It generally
consist of three parts: a condition, an expression to execute if SyntaxHere is the syntax for ternary operators (CONDITION) ? (EXPRESSION If True) : (EXPRESSION If False); Now compare that to a standard If/Else statement: if (CONDITION) { ExamplesLet’s look at transforming a simple if/else into a ternary operator in a function called isEven. For example, if the number I pass in is // If/else statement It’s generally considered best practice to avoid nesting ternary operators(if you can) because it can be hard to read at times. Let’s take at an example where ternary operators can quickly blow up. // If/Else Statement As you can see with the example above, this might be one of the moments where ternary operators may not necessary be the best option since it slightly affects readability. Perhaps an if/else, switch statement or
lookup table would be a better option. Let’s look at another example of avoiding uneeded ternary statements where we check and assign a port number if it exists from the environment else set a default port // If/Else statments NOTE!: While ternary operators are neat please use them wisely. In addition, ternary operators can also be used as a way to selectively render certain React components depending on which conditions are met.
ConclusionToday we learned a few control structures available in JavaScript. We learned how to use ternary operators, switch statements, and creating/using a lookup table. We also learned to implement a lookup table using If you enjoyed this article please share this with other folks and give me a clap or follow me on Medium. If you have any questions, comments, or concerns then please feel free to leave a comment. As always keep coding and git learning! Resources
What are the 4 control structures?if-else conditionals, case statements, for loops, and while loops are all control structures.
What are the three types of control structure in JavaScript explain?There are three Iterative statements: WHILE, DO-WHILE and FOR. Let's understand each with syntax. one of the control flow statement, which executes a code block when the condition is satisfied. But unlike IF, while keeps repeating itself until the condition is satisfied.
What are control structures examples?There are three kinds of control structures:. Conditional Branches, which we use for choosing between two or more paths. ... . Loops that are used to iterate through multiple values/objects and repeatedly run specific code blocks. ... . Branching Statements, which are used to alter the flow of control in loops.. What are the 3 main control structures?Flow of control through any given function is implemented with three basic types of control structures:. Sequential: default mode. ... . Selection: used for decisions, branching -- choosing between 2 or more alternative paths. ... . Repetition: used for looping, i.e. repeating a piece of code multiple times in a row.. |