Comments

5 Common JavaScript Gotchas That You Should Avoid

JavaScript Gotchas

JavaScript Gotchas

Today JavaScript is the most popular language among developers. Modern frontend development has benefited a lot from JavaScript and its rise. It has definitely emerged as one of the most sort after skill in the programming world with plenty of job opportunities.

Learning JavaScript at the beginning may seem easy, but the language comes with own sets of nuances and complexities. In this post, we are going to discuss 5 common JavaScript gotchas and how you can avoid them.

1. Equality (== vs. ===)

Triple Equality === 

Coming from a Java background, I was initially thrown off to see the triple equals operator. With the triple equals operator, we are checking for both type and value. This is referred to as strict equality.

Let’s look at some examples to understand how the strict equality works.

if (6 === 6)
// returns true

In this example, we are comparing two numbers. Here the value is the same and equal. Also the type is number and equal as well. This makes it return a true.

Alright, let’s take a look at another example.

if (6 === '6')
// returns false

In this case, it returns a false. This is because although the value is the same, the types are different. The types are number and string, and they don’t match. Hence the condition returns a false.

It is generally better to use === and !=== to check for both type and value.

Double Equality ==

Now, let’s take a look at the double equals operator. When checking for double equals in JavaScript, we are testing loose equality. This means that we only compare the values, and not the type.

Let’s go back to our previous example, and replace the triple equals with double equals.

if (6 == '6')
// returns true

You can see now with the double equals, this returns a true. Behind the scenes, JavaScript converts the string ‘6’ to type number. Once the type conversion is done, this test returns a true. This type conversion is called type coercion.  Let’s take a look at another example.

if (null == undefined)
// returns true

The example above also returns true and qualifies as equals with a loose check. Those new to JavaScript may see some undesired outcomes from their code because of the loose equality and type coercion. Hence it is best to use strict equality for equality checks.

2. Confusion in using var vs. let

There is often confusion between the use of var vs. let. Some JavaScript newbies think they can use them interchangeably without fully understanding their differences. Let’s take a look at how they are different.

var

Before ES6 (ES2015) few years ago, there was only one way to declare variables and constants in JavaScript, which was using var.

To understand var, we need to first learn how they are scoped. Let’s look at a simple example below to learn more about it.

function begin () {
 for (var i=0; i<5; i++) {
  console.log(i) 
 }
// i is accessible outside the for loop
 console.log(i)
}

Now, in our code snippet above, we have a variable i that is declared inside the for loop. The console output that you will see for this code is shown below.

0
1
2
3
4
5

What is strange here is that, although the variable i is declared inside the for-loop, it is still accessible outside the scope of the for-loop. This is because the var variables are accessible within the scope of the function that they are declared.

var variables have a function-scope, if they are not declared within a function, they have a global-scope.

let

After ES6/ES2015, JavaScript introduced let to overcome the problems faced with var.

Typically, we want our variables to be scoped within a block of code. If we declare a variable within a block of code say a for-loop, we want it to live within that block and be inaccessible outside of it. This behavior can be achieved in JavaScript using the let keyword.

Let’s go back to our previous example, and replace the var with let instead.

function begin () {
 for (let i=0; i<5; i++) {
  console.log(i) 
 }
// i is not defined and will return an error
 console.log(i)
}

The output that we see for this example after replacing it with let will be slightly different than the previous example.

0
1
2
3
4
Uncaught reference error: i is not defined

The console log that happens outside the for-loop block returns an error. It does not know what i is, and returns that i is not defined. This is a desirable output that we get with the use of let instead of var.

let is block-scoped and variables declared within a block of code cannot be accessed outside of it.

I hope this clears up the difference between var and let, and their usage. The fundamental difference is in their scope.

3. The ‘+’ can be used for both addition and string concatenation

Typically, we think of the ‘+’ symbol as the sign for adding numbers. But in JavaScript, we can use the same symbol for concatenation of strings. You have to use it with caution when you are operating with both strings and numbers together.

Let’s take a look at some examples to see where you may go wrong.

var a = 10;
var b = '30';
var c = 40;
return a + b; // returns '1030' (concatenation)
return b + c; // returns '3040' (concatenation)
return a + c; // returns 50 (addition)

In the examples above, when there is a string involved, the ‘+’ sign always concatenates the string, even if the other variable is a number. We can see that 10 + ’30’ results in a string ‘1030’. Those new to JavaScript, may encounter this problem since this is not common in other languages.

If you use the ‘+’ to add an integer and a string, it will result in the concatenation of both.

To avoid this concatenation, if your original intention was to add the variables, make sure to convert the string to an integer.

4. What is the difference between undefined and null?

Most programmers are aware of null. It is common in other programming languages. But what on earth is undefined in JavaScript?

Undefined usually means a variable has been declared, but not defined.

let value;
console.log(value);
// undefined

In this case value has been declared but it is not assigned a value. This results in undefined.

I have seen many codebases with a lot of null checking against properties that are uninitialized. This is wrong and will result in unexpected behavior. Uninitialized properties in other languages get a default value of null, but in JavaScript they are undefined. What makes it even more misleading, is that if you did a loose equality check of (x == null), even if x is undefined, it will return true. This is because of the type coercion that we discussed in the previous point.

null is not strictly equal to undefined. But null is loosely equal to undefined.

null !== undefined
null == undefined

Isn’t JavaScript a funny language with all these quirks?

5. Semicolons can be a problem sometimes

Semicolons  are used in several programming languages. JavaScript comes with the automatic semicolon insertion feature. Generally, you can omit semicolons most of the times. But beware of the automatic semicolon insertion feature. It took me a while to realise that JavaScript has this annoying feature.

Take a look at this code sample for example:

return 
{
  a: 50
}

Can anyone guess what is wrong with this piece of code?

You might think that it would return the object literal, but it actually returns undefined. This is because automatic semicolon insertion takes place making it an empty return statement.

This is how the code looks after the semicolons are inserted.

return;
{
  a: 50
};

Strange isn’t it. You can add a linter rule to remind you about this. You can add a rule to ensure that a new line never begins with an opening brace, bracket or template string literal. Your code should instead look like this:

return {
  a: 50
}

Conclusion

JavaScript is easy to pick up, but hard to master. It takes a while to learn the quirkiness and nuances of the language before you master it. If you are looking for an awesome course to master you JavaScript proficiency, I highly recommend Mosh’s courses on JavaScript. Checkout the bundle below for Mosh’s JS courses.

Mosh’s JavaScript Courses Bundle

If you enjoyed this post, share and spread the word. You can follow me on twitter at @AdhithiRavi

Checkout this space for more fun articles!

Adhithi Ravichandran is a Senior Software Engineer based in Kansas City. She is currently working on building mobile apps using React Native for critical healthcare scenarios. Adhithi is a regular conference speaker at various tech conferences. Adhithi graduated with a Masters degree in Computer Science from the University of Kansas and has been in the tech industry for over 7 years. She has worked on several technologies over the years, and one of her recent favorite is React Native.
Tags: , ,

Leave a Reply

Connect with Me
  • Categories
  • Popular Posts