Avoid These Common JavaScript Mistakes

Thomas Karatzas
codeburst
Published in
2 min readJul 21, 2017

JavaScript is one of the most popular programming languages in today’s industry. If you wish to dive into this language, here are a few mistakes to avoid.

1. Using “==” instead of “===”

This is probably the most common error when people start with JS. The difference between the two is that “==” will convert the type and “===” will not.

In general, you should always use the “===” also known as the Strict Equality Operator. It allows for more predictable behavior and fewer hard to track bugs.

2. Using typeof

In short, you should only use typeof to check if a variable is defined. Otherwise, you will have very inconsistent behavior.

As you can see, the alternative can handle more general cases and allows you to be more flexible (ie: this will work with you own classes).

3. Using “this” incorrectly in a class

This is probably the most common blocking point for people getting started with JavaScript when they come from a language like Java. In Java, “this” always refers to the current object. This is not the case in JavaScript. In fact, “this” has 5 different ways of being bound.

Theses 5 cases make sense and are easy to reason about. However, the second case is considered a design flaw because it leads to the following problem.

4. Not using anonymous wrappers

JavaScript only has function scope and everything is shared in one global namespace. With large projects, this can introduce hard to track bugs.

To avoid this, you can use what are called anonymous wrappers. Essentially, they are functions that are called immediately. Since anonymous functions are considered values, they need to be evaluated before they can be callable.

Not only do they protect you from name clashes, but they can help you better organize your code.

5. Incorrectly Iterating Through Keys of an Object

There are several ways to iterate through the properties of an object. You can use Object.keys, Object.entries or a for in loop.

6. Omitting Semi-Colons

JavaScript does add semi-colons if they are omitted but it can actually mess up your code and cause strange errors. Here are the two most popular cases:

You should use a linter to make sure semi-colons are not forgotten. In addition, always put the braces on the same line of its corresponding statement to prevent unwanted behavior.

Sources:

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Thomas Karatzas

Software Engineering at @McGillU. Interned @Microsoft. VP Internal @AiMcgill