What are control structures in javascript?

What are control structures in javascript?

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:

  • If/Else Statements
  • Switch Statements
  • Lookup Tables
  • Ternary Operators
  • …and many more

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 Statements

An 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 ) {
statement
}
alternative statement

This could be visually represented as follows:

What are control structures in javascript?

Pic from Eloquent JS

As 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 === evaluates whether this value is 0 and evaluates to a true or false boolean value.

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:

  • Any number divisible by three is print the word Fizz
  • Any number divisible by five print Buzz
  • Any number divisible by three and five print FizzBuzz

Visually, this could be represented as follows:

What are control structures in javascript?

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 Statements

What are control structures in javascript?

Pic from Google

Similar 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.

Syntax

switch (expression) {
case clause1:
// Statements to be executed
break;
case clause2:
// Statement to be executed
break;
case clause3:
// Statement to be executed
break;
default: // Optional but usually considered good practice
// Statement to be executed if no cases match
}

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 break is important because it prevents the next case from executing after a criterion is met.

Examples

A simple example of switch statement with traffic lights:

Here is another example evaluating a few HTTP codes, handling client error responses(4XX):

The above is a fairly simple usage of a switch statement. You can find additonal use cases/uses for switch from the mdn doc here.

Lookup Tables

What are control structures in javascript?

Pic from Google

Lookup 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
tableName[KEY] ?? (DEFAULT EXPRESSION/STATEMENT IF NOT FOUND);
// Map
mapName.get(KEY) ?? (DEFAULT EXPRESSION/STATEMENT IF NOT FOUND);

The way nullish coalescing operator works is that it will return the value of the left-hand side of ?? if it is NOT null or undefined, else it will return the default case on the right-hand side.

We will look at two distinct approaches to creating a lookup table:

  • Object
  • Maps

Lookup Table with JavaScript Object

Let’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
switch (httpStatusCode) {
case 400:
statusCodeResponse = `${httpStatusCode} Bad Request: The server could not understand the request due to invalid syntax.`;
break;
case 401:
statusCodeResponse = `${httpStatusCode} Unauthorized: The client is unauthenticated and must be properly authenticated.`;
break;
case 403:
statusCodeResponse = `${httpStatusCode} Forbidden: The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource.`;
break;
case 404:
statusCodeResponse = `${httpStatusCode} Not Found: The server can not find the requested resource.`;
break;
default:
statusCodeResponse = `500 Internal Server Error: The server has encountered a situation it does not know how to handle.`;
}

Let’s take this and throw each clause/statements into an object as a property.

Next, create a function called getHttpStatusCode that will return the status code and message response based on the status code input.

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 clientResponseCode[status]. If clientResponseCode[statusCode] evaluates to null or undefined, then it will retrn it's right-hand side operand which serves as a default case.

Lookup Table with JavaScript Map

Instead of using a JavaScript Object as a Map, we are now going to implement the same lookup table with an actual, native Map data structure. Historically, especially ES5 days, developers used to implement an Object as a Map. There are some distinct disadvantages to this approach, especially as your table grows, there is a potential for collisions to occur. Performance wise, a Map data structure is ideal for situations for frequent additions and removals of key-value pairs. Please see this link if you are unfamiliar with JS Maps and also look at the section comparing Maps vs. Objects here.

The syntax to instantiate a Map data structure is as follows:

// Map
const someMap = new Map();
// Setting properties
someMap.set(KEY, VALUE);
// Instantiate Maps with Arrays
const map = new Map(
[key1, val1],
[key2, val2],
[key3, val3]
);

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 Object , with the difference being reading the values of the map.

Ternary(Conditional) Operators

Ternary 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 truthy, and an expression to execute if falsy. However, this does not mean that it is a comprehensive replacement for all if/else statements. Sometimes for the sake of readability you should really just keep it simple and stupid. Please follow Airbnb Style Guide rules: 15.6 & 15.7.

Syntax

Here is the syntax for ternary operators

(CONDITION) ? (EXPRESSION If True) : (EXPRESSION If False);

Now compare that to a standard If/Else statement:

if (CONDITION) {
// EXPRESSION If True
} else {
// EXPRESSION If False
}

Examples

Let’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 even then return true and false if otherwise.

// If/else statement
const isEven = num => {
if (num % 2 === 0) {
return true;
} else {
return false;
}
};
// Ternary Operator
const isEven = num => (num % 2 === 0 ? true : false);

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
const determinetTrafficLightCondition = lightColor => {
if (lightColor === 'Red') {
return 'stop';
} else if (lightColor === 'Yellow') {
return 'slow down';
} else if (lightColor === 'Green') {
return 'go';
} else {
return `ERROR: ${lightColor} is not recognized.`;
}
};
// Nested Ternary operator - OKAY?
const determineTrafficeLightCondition = lightColor => {
return lightColor === 'Red'
? 'stop'
: lightColor === 'Yellow'
? 'slow down'
: lightColor === 'Green'
? 'go'
: `ERROR: ${lightColor} is not recognized.`;
};
// Split Ternary operator - SLIGHTLY BETTER?
const getTrafficLightConditon = lightColor => {
const isRed = lightColor === 'Red' && 'stop';
const isYellow = lightColor === 'Yellow' && 'slow down';
const isGreen = lightColor === 'Green' && 'go';
const isError = `ERROR: ${lightColor} is not recognized. Blinking Red!`;
return isRed || isYellow || isGreen || isError;
};

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. Rule of Thumb: Keep it simple!

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 3000.

// If/Else statments
const port = 0;
if (process.env.PORT) {
port = process.env.PORT;
} else {
port = 3000;
}
// Uneeded Ternary Operator
const port = process.env.PORT ? process.env.PORT : 3000;
// BETTER
const port = process.env.PORT || 3000;

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.

Conclusion

Today 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 Map and Object. The list shown here is by no means comprehensive. Each control structures have their use cases and respective benefits/costs. The objective of this article is to show you different ways to control the flow of your code, it is by no means a comparison.

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

  1. Eloquent JavaScript
  2. Maps MDN Docs
  3. Switch MDN Docs
  4. If/Else MDN Docs
  5. Ternary Operator
  6. Airbnb JavaScript Style Guide

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..