UI Development

Silly Web Development Errors

Have you ever been stuck in your code? There are times when you don’t necessarily understand what’s going wrong. If you are stuck somewhere in the code and cannot figure out what’s going wrong, it’s always good to

  1. Look answers online (StackOverflow, Quora, Medium)
  2. Do not shy away in asking for someone’s help

To make a mistake is human. But, we must follow the best approach to resolve it. Let’s discuss a few silly errors we might be making while writing code:

Referencing to this inside setTimeout() and setInterval():

The keyword this is of great significance in JavaScript. And it is a bit confusing too. The keyword this, in simple words is a reference to the object which is calling a function. We don’t need to declare this, it gets automatically created when we define a function. To read more about this keyword refer to this article – The Complete Guide to this in JavaScript.

setTimeout() and setInterval() are native functions in JavaScript. setTimeout() is used when we want to execute a piece of code after waiting for some time. setInterval() is used when we want a piece of code to execute repeatedly after a fixed time has elapsed. To read more about this – setTimeout MDN and setInterval MDN.

When setTimeout and setInterval are called outside a function, they by default refer to the global object, which in case of web browsers is the Window object.

Let’s see what happens when we call these native functions inside our own function. Let’s take an example, where we have a set of colors. These colors will be used to change the background color of the button, once it is clicked.

Running the above code, will not achieve the desired result.

You can see from the console statements that outside setInterval() this refers to the button object but, inside setInterval() we see that it is still referring to the global object. To use this inside setInterval() or setTimeout(), its best to use the following approach:

  • Using a helper variable: We can save the value of this inside a variable and then use it inside the setInterval() function.

  • Using arrow functions: Arrow functions, unlike other functions, do not have their own this. They instead use the concept of lexical scoping that is this inside an arrow function will refer to the surrounding scope.

Writing code inside frequently called events

Events are used to help the user interact with the application. We add event listeners to handle the various events triggered by the user. The different types of events can be a simple click on the DOM, key events(onkeypress, onkeydown, onkeyup), mouse events(onmouseover, onmouseout), onscroll, resizing the window, etc. Events like scrolling, resizing, are fired frequently in an application, and defining handlers or code inside these events can cause problems with the efficiency of the page. Here’s a simple example to see what number of times the scroll event gets fired.

Initially, the scroll count is zero.

If you see the screenshot, we have scrolled down and the count has moved up to 36 suggesting that we are executing the same set of code 36 times.

A few years back, users experienced an issue while using Twitter. When they scrolled down in the application, the content was freezing and making the application unresponsive. You can read about this here – Learning from Twitter. In conclusion, it’s a bad practice to attach handlers or write expensive DOM operations on such events. It’s best to follow some of these approaches:

  • For every addEventListner, use its counterpart removeEventListener which ensures to clean up unused events.
  • We can throttle a scroll event using custom events or requestAnimationFrame or setting a delay using setTimeout
  • Using a debounce function to control the number of times a function can fire.
  • We can use passive events for the scroll event

Writing a media query using 768px as max-width rather than 767px 

I recently encountered this error while writing media queries for my application. Lets first understand what media queries are.

Media queries were introduced with CSS3 since responsive web pages became the new trend. To put in simple words, a media query is a set of styles that will be implemented only when the device is a specific height, width, orientation, or a combination of these.

To infer how 767px is the correct choice, we need to understand that we are trying to have a different style for mobiles from the one that we have on desktop or iPad. The following example is from the project that I recently worked on. Let me first state the requirement here. There are three elements – two buttons and search input. For desktop and iPad we need to show them horizontally aligned whereas, for mobile, we need the search input on top and the two buttons at the bottom. Please refer to the screenshots.

Layout for mobile should change to –

Let’s write a quick code for this

Now, we write the CSS code for this

In the above code, we set the max-width as 768px. So, whenever the device width is equivalent to 768px, it will apply the set of properties defined in the media query. Our code is not wrong but not per the requirement. We might be thinking for some reason that it will only work for mobile but if we open the browser and inspect our code we will see it working for iPad as well.

So, to correct our code here, we need to just change the value of max-width in the media query:

Now, if you open the code on the iPad, you will see a similar layout as on desktop.

If you open on mobile, you will see the different layout, hence meeting the requirement.

Animating an element which is either displayed as block or none:

Animations are a brilliant way to attract more users, but it can be tricky. The most basic animation is to hide/show an element. Certain properties cannot be animated for instance the display property in CSS.

Let’s look at an example. We want to show additional information but only when the user clicks on a button or link. Since the additional information cannot be visible initially, the first thought that comes into our mind will be to five the additional information element CSS property display: none and then add the CSS property display: block on clicking the button along with some animation. Let’s try doing that.

On executing the above code you will see that on clicking the button the element will show up but without any animation. This is because of the property display: none. The element was never present on the DOM so the change in width is never initiated. If we remove the display property from the CSS code, the animation will work fine.

An additional point to note while working with animations is that we cannot animate a CSS property with the value auto as animation only works with fixed values. Here’s a link to check what CSS properties we can animate- CSS Animated Properties.

Attaching events to elements for all resolutions

A lot many times when we code for different resolutions, we try to give a simple if-else condition for events that are meant to happen only for a particular resolution say phones or iPads. We attach the events inside these conditions. It’s important to remember that a device can always be rotated and the resolution will change significantly in many cases. So, the order in which we write the code matters. Let’s see an example

We have a simple toggle button for the header of the application. This toggle button will be visible only for resolution less than 850px. When we click on the button, it will open a left menu bar.

We know the requirement and if we are following it, we can write something like this

Since the toggle button is only visible for resolution less than 850px, we might think it’s best to attach the click event only when the device width matches our requirement.

Now, if we run this, and move to a mobile device, it works just fine. Let’s check it in an Ipad. It’s working fine there as well.

So, what could go wrong? Let’s consider that the user opened this on an iPad but the orientation of the device was landscape, or maybe on a larger mobile device. The styles will be similar to the desktop and the user will be able to navigate. But, as soon as we switch the device orientation to portrait, this won’t work. Nothing will be triggered when we click on the hamburger menu.

Where did we go wrong? When the code is initially loaded, it checked for the condition and since our device-width matched that of the desktop width, we didn’t face any issue. But, if we switched to the portrait, the condition won’t be checked again as the page will not be reloaded. And, since we defined the click event handler inside the condition, we won’t be able to execute it.

What needs to be done? We need to define the click handler first and then define any condition if required. Here’s the correct code:

Now, if you try switching from the iPad landscape to the iPad portrait, it won’t cause any problems. Here’s the full code for you to try.

Using loose equality “==” rather than strict equality “===”

In our day to day coding expeditions, we all implement comparisons between different data types. Javascript gives us two equality comparison operators “==” and “===”. They both can be used to compare values, the only difference is that “===” checks for type as well. If two values are compared and they both have the same type and content then === will return true otherwise false. This is known as strict equality. Whereas “==” will only check for the content and not the type. This is known as loose equality.

When we use “==” for comparison it performs type coercion. That means that it will attempt to convert the type of element which can create a large number of problems. Let’s see a few scenarios.
Imagine you are comparing two values and it should evaluate as true only when the content is the same. We might think that here we can use loose equality, but what if both the values that are being compared are null or undefined. Refer to the following screenshot.

Your application might want to handle undefined values in a separate way as compared to null values. But, if we are using loose equality it will handle both the values the same way. Next, let’s see how loose equality behaves in the case of boolean values. Refer to the following screenshot

Let’s see a few more, to see how loose equality might return abrupt results.

It is strictly advised to use strict equality comparison wherever needed which in turn will assure a true equality test of values in your application. Errors like these are hard to debug and are time-consuming.

Writing switch cases without using break

A switch statement is used whenever we have multiple conditions to check for a single value. If you look at the definition of switch online(Switch case), you will see that in the syntax it says that the break keyword is optional. This doesn’t mean that we do not use it. Missing a break statement can lead to an error on your part of the application.

Let’s see an example here. We have an application that offers different services to a user depending upon their membership.

In the above example, we missed a break statement for the renewed user case. If we run this, we will see that both the renewed and expired switch case will evaluate to true and run their respective codes. So, in the end, even if the application was supposed to renew a particular user, it will end up deleting that user altogether. 

Another point to note is that an unexpected value might cause our application to run into an error. The default case in a switch statement can be used for such error handling that is in case no value is matched.

Conclusion

This blog covers only a small number of errors. It is a reflection of the mistakes we as web developers make and how we can avoid them. Even though the above-discussed errors might look small, they are of great significance and help build the foundation for our development. In the end, it is a quality code that matters.

About The Author