This is post # 51 of the series, dedicated to exploring JavaScript and its building components. In the process of identifying and describing the core elements, we also share some rules of thumb we use when building SessionStack, a JavaScript application that needs to be robust and high-performing to help companies optimize the digital experience of their users.
In programming, conditional statements are logical statements or commands that handle decisions based on certain conditions. They do this by performing different computations or actions depending on whether the developer-defined condition turns out to be true or false.
JavaScript also has conditional statements which determine whether or not a piece of code can run depending on the status of the developer-defined conditions. Since JavaScript has a lot of conditional statements, it can become confusing as to which statement should be used in certain conditions.
Conditional statements are used for controlling how a piece of code should work. If a condition is met the code should do something, but in a case where the conditions are not met something else should happen. Iterators are used for repeating a particular line of action over and over based on a statement without violating the DRY (Don’t Repeat Yourself) principles. This ability is most useful to developers when they want to perform tasks repeatedly without having to repeat themselves. If a condition is met, then the code will continue running until the condition becomes false.
JavaScript conditional statements and iterators
There are different types of iterators and conditional statements in JavaScript, just as they are in other programming languages, we have:
- If and else statement
- Switch statement
- For loop
- While loop
Each of these statements has different use cases. Let’s explore the JavaScript conditional statement in depth.
“If / else” statements
The if / else conditional statements execute a block of code if a specified condition is met (that is the condition is true) or executes another block of code if the same specified condition is not met (that Is the condition is false). For example, if you want to write a piece of code that checks for the age of users and prints out an output that says “hello you are an adult” if the age is up to or print “you are not 18” if the age is below 18. Then you can do something like this;
https://medium.com/media/d31ed076b818ad674606d19564243036/href
This statement allows developers to use the following conditional statements:
- if statement.
- if else statement.
- else if statement.
“If” statement
The if statement is used to specify a block of code to be executed if a condition is met. The syntax for the if statement is shown below:
https://medium.com/media/fbab0e3624085b0a92a08fe25fd7a8d9/href
Using an if statement without an else statement means that they’ll be no fallback code to be executed if the condition is false. For instance, we can compare the value of variables and execute a block of code only if the condition of comparison is true:
https://medium.com/media/1b31f5ba0670f1157bc202899062ba6d/href
Since the condition of comparison is not true, the block of code in the if statement won’t be executed. An else statement serves as a fallback for every if statement. So, in our example above the else statement will execute a block of code when the condition is false.
“Else” statement
The else statement is used to specify a block of code to be executed if a condition is not met. The syntax for the else statement is shown below:
https://medium.com/media/e19fe2c16afb69821e6a06b73fcb1c48/href
We can incorporate the else statement to the if statement we executed earlier so that we have a fallback when a condition is not met.
https://medium.com/media/46614fed2b8435d7c58d4153f2398e91/href
“Else if” statement
The else if statement is used to specify a new condition to be tested if the first condition is not met. This can be used when there’s more than one condition to be tested. The syntax for an else if statement is almost the same as the if statement, just that in place of the if we make use of an else:
https://medium.com/media/3ca069f4022371c8857d4604ad6caf71/href
An example of how the else if statement is a grading system for students is shown below:
https://medium.com/media/f6def60e041b65e66df0e7b0dc478142/href
The code above will display the grade of the student when you enter their score.
“Switch” statement
The if/else statement is useful when the conditions to be tested are minimum. That is, the if/else statement quickly gets ambiguous and confusing when the logical statements become large like the else if example we discussed earlier. This is where the switch statement comes in.
The JavaScript switch statement is used in performing different code actions based on different conditions (cases), for example, we have blocks of code, but we want each block of code to be executed only when a case is true (matches the switch expression), then we can use the switch statement.
The switch statement has the same functionality and the same syntax as the if/else statement, but in the case of the switch, you won’t make use of the else statement, instead, you will use the case statement. So the switch statement generally has a syntax like this:
https://medium.com/media/f24122919f78b90f9d4fc59a2afcde3c/href
The reason for the break keyword is to tell JavaScript to stop executing the code when the first condition is true. For instance, if we have two cases (case A and case B) in a switch statement, without a break keyword between them, both will be executed if case A meets the requirement and case B does not meet the criteria.
In most cases, you can specify default as a fallback if none of the conditions specified were met in the defined cases. The default keyword is used for this purpose, something like this:
https://medium.com/media/108feb1547037e1324bc40e54490f49c/href
From the example below, we can get the exact day of the week with the switch statement:
https://medium.com/media/9f5aa3a61dcae6fea0beff1b61c10570/href
Now from our example, we are looking for the current day of the week, using the new Date() and the getDay() method. The getDay() works with specific numbers that correspond to the days of the week, we have 0 which corresponds to Sunday down through 6 which corresponds to Saturday. According to the day in your calendar, the cases will be matched to the switch statements and if any of the case matches the expression then the block of code under such case will be executed.
Let’s replicate our grade example using the switch statement.
https://medium.com/media/8736a5b6dbe1673af67b60406c5589be/href
From the example above the user should input any number. To use this kind of switch statement you have to specify a boolean (True) inside the switch expression.
“For” loops
In JavaScript, loops are a type of iterators, used for doing a particular action over and over again. They are pretty much powerful if you want to repeat actions and still keep the code in line with the DRY principle. There are different types of loops available in JavaScript and amongst them is the for loop. The JavaScript for loop has the following syntax:
https://medium.com/media/0780fcefdad7f8984d3f8e7e4227a67f/href
- The first expression is executed before the code block runs. Most times this statement is used for setting variables. It is possible to omit the first expression if you have your variables declared already before the loop.
- The second expression is where the condition necessary for the code block to be executed is specified. This is where you can do most of your comparison. It is not mandatory to use the second expression in the loop, but if for any reason you should omit the second expression in the loop then, you should provide a break statement, so that your loop won’t run forever and your browser won’t crash.
- The third expression in the for loop is executed every time the block code inside the loop has been executed. Most times the third expression increments the value of the variable (you can do any type of modifications to the variable). You can omit this expression if you want to do the increment inside the curly brackets, using the block of codes.
The example below shows a for loop without the third expression. This code will run forever because num is 0 and 0 is always less than 15:
https://medium.com/media/2c98eb3311c5f911a49efc44658f024e/href
This statement allows developers to use the following loops:
- for loop
- for/in loop
- for/of loop
“For of” loops
The for of loop allows developers to create a conditional loop iterating over iterable objects and user-defined iterables. The for of loop takes two expressions: a variable and an iterator:
https://medium.com/media/da9b83f805fd90b19ff5a7185c917e16/href
The example below shows how to use the for of loop in an iterable, like an array.
https://medium.com/media/2a258f39729a836f5e91bf55210e65af/href
The code above will loop over the content in array1 to print 1, 20, 13, 15.
“For in” loops
The for in loop iterates over all enumerable properties of an object if a condition is met. By default, all properties of an object created by a simple assignment or a property initializer are enumerable.
https://medium.com/media/88f73da360ffc5f2bafb10092d1c65db/href
The example above will log the keys and values in the object above.
“While” loops
The while loop will continue until a specified condition becomes false. The syntax of a while loop is shown below:
https://medium.com/media/a4a41be4ed8b5b388b5a8f0432aad959/href
Unlike the for loop where we have three statements, the while loop accepts only one parameter and that parameter will be the condition for running the code. If the condition should turn false, then the loop will stop.
Let’s look at the code below, which is an example we looked at earlier in the for loop.
https://medium.com/media/b8be42070ee0873f3ab902c4409bd3bc/href
The loop will look at the variable we have declared before and try to compare it with the condition we have inside the parenthesis, in the case above it will try to see if num is less than 15, if it is, it will continue to execute the block of code inside the curly bracket, it will continue this way until the specified condition becomes false then it stops.
“Do while” loops
You can also specify a loop in JavaScript using the do…..while statement. In the do while loop, the condition is checked at the end of the loop. The syntax for a do….while loop looks like this:
https://medium.com/media/8dade8a6a40d0940a27b81f86214a66d/href
In a do…..while loop the statement comes before the condition itself. What happens is that the statement will be executed first before the evaluation of the condition. After the first execution of the statement, the condition is then evaluated and if the condition remains true then the statement is executed again, and it will continue that way until the condition is no longer true, then the loop stops
When to use each statement
Since we have a lot of JavaScript conditional statements, this section categorizes conditional statements into iterators and conditional statements, explaining when to use them.
Iterators
JavaScript iterators are used for repeating actions. It consists of for, and while loops. Although for loops and while loops can be used interchangeably, it is better if you use the for loop when you know the expected number of times the loop should run. This is because the for loop breaks out when the number of times it was supposed to run is exhausted. However, if you do not know the number of times a loop should run (that is breaking from the loop depends on a condition being false) then you should make use of a while loop.
Conditional statements
Generally all conditional statements are used for decision making in programming. We have different conditional statements that are used for this purpose, like the if…. else statement and the switch statement. The switch is sometimes preferred over the if….else statement in cases where you do not want to use a heavily nested if construct. This is because it makes your code ambiguous and difficult to read.
Best practices when using conditional iterators
- Avoid heavy nesting while creating a loop or a conditional statement, as over nested loops and conditionals will cause a slowdown in the execution of the code
- Do not use a for loop for iteration when you don’t know the number of times the code should be executed. Use a while loop instead.
- While using the switch statement in evaluating a range of options, always remember to make use of the true boolean expression.
Conclusion
JavaScript conditional and loop statements are very important when it comes to keeping our code in line with the DRY principle. They are very handy when it comes to repeating operations.
Selecting the right conditional statements and loops does not only make your code more readable but it can lead to much better efficiency and performance.
Even if you feel like the proper decisions have been made, it’s always necessary to verify that this is indeed true and your users have a great experience with your product.
A solution like SessionStack will help you determine and further optimize the experience of your users by allowing you to replay their journeys as videos, showing you how your users actually experience your product. You can quickly determine whether your product is performing according to their expectations or not. In case you see that something is wrong, you can explore all of the technical details from the user’s browser such as the network, debug information, and everything about their environment so that you can easily understand the problem and resolve it.
There is a free trial if you’d like to give SessionStack a try.
SessionStack replaying a session
If you missed the previous chapters of the series, you can find them here:
- An overview of the engine, the runtime, and the call stack
- Inside Google’s V8 engine + 5 tips on how to write optimized code
- Memory management + how to handle 4 common memory leaks
- The event loop and the rise of Async programming + 5 ways to better coding with async/await
- Deep dive into WebSockets and HTTP/2 with SSE + how to pick the right path
- A comparison with WebAssembly + why in certain cases it’s better to use it over JavaScript
- The building blocks of Web Workers + 5 cases when you should use them
- Service Workers, their life-cycle, and use case
- The mechanics of Web Push Notifications
- Tracking changes in the DOM using MutationObserver
- The rendering engine and tips to optimize its performance
- Inside the Networking Layer + How to Optimize Its Performance and Security
- Under the hood of CSS and JS animations + how to optimize their performance
- Parsing, Abstract Syntax Trees (ASTs) + 5 tips on how to minimize parse time
- The internals of classes and inheritance + transpiling in Babel and TypeScript
- Storage engines + how to choose the proper storage API
- The internals of Shadow DOM + how to build self-contained components
- WebRTC and the mechanics of peer to peer connectivity
- Under the hood of custom elements + Best practices on building reusable components
- Exceptions + best practices for synchronous and asynchronous code
- 5 types of XSS attacks + tips on preventing them
- CSRF attacks + 7 mitigation strategies
- Iterators + tips on gaining advanced control over generators
- Cryptography + how to deal with man-in-the-middle (MITM) attacks
- Functional style and how it compares to other approaches
- Three types of polymorphism
- Regular expressions (RegExp)
- Introduction to Deno
- Creational, Structural, and Behavioural design patterns + 4 best practices
- Modularity and reusability with MVC
- Cross-browser testing + tips for prerelease browsers
- The “this” variable and the execution context
- High-performing code + 8 optimization tips
- Debugging overview + 4 tips for async code
- Deep dive into call, apply, and bind
- The evolution of graphics
- Dockerizing a Node.js application
- A deep dive into decorators
- Best practices for data compliance
- Proxy and Reflect
- SVG and its use cases (part 1)
- Class static blocks + 6 proposed semantics
- Introduction to Graphs and Trees
- Introduction to PM2, Strongloop, and Forever + 4 tips for Production Process Managers
- Аdvanced SVG capabilities (part 2)
- Тhe publisher-subscriber pattern
- Stacks and Queues + tips for efficient implementation
- Lists vs Blockchain + implementation practices
- The module pattern + comparing CommonJS, AMD, UMD, and ES6 Modules
How JavaScript works: the different types of conditional statements + 3 best practices was originally published in SessionStack Blog on Medium, where people are continuing the conversation by highlighting and responding to this story.