Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is JavaScript
3.
Common Mistakes
3.1.
Adding Two Different Datatypes
3.2.
Floats Misunderstood
3.3.
Loose Comparison
3.4.
Undefined vs Null
3.5.
Variable Scope Misunderstood
3.6.
Callbacks are not Synchronous
3.7.
{} === {} is True or False?
3.8.
Breaking A Return Statement
4.
Good Practices to Adopt
4.1.
Avoid Global Variables
4.2.
Initializing Variables
4.3.
Stay Alert for Type Conversion 
4.4.
Avoid Declaring Strings or Arrays as Objects
5.
Frequently Asked Questions
5.1.
How are new objects created in JavaScript?
5.2.
What is the variable naming convention followed in JavaScript?
5.3.
When to use var, let, and const?
5.4.
What is NodeJS?
5.5.
What are some most common mistakes one makes while writing code?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Common mistakes in JavaScript

Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Hey Ninjas!! I’m sure you are familiar with JavaScript. Maybe you just know the gist of the language, maybe you are proficient with it, or maybe you are a newbie. As may be the case, today we will discuss some common mistakes people make while writing JavaScript codes. So even if you are a newbie, this will be helpful for you in the future.

Common mistakes in Js

Also Read, Javascript hasOwnProperty

What is JavaScript

Javascript is a cross-platform (i.e. used both on the client side and server side) scripting language, which is primarily used for enhancing the interaction between a user and a webpage. It is most widely used in the World Wide Web and other game development stuff.

JavaScript or JS is quite popular among IT professionals, software developers, etc. But have you wondered if there are some things you’ve been doing wrong? or when you encounter some error or see unexpected results? 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Common Mistakes

Let’s discuss some common mistakes people make in JavaScript. 

Adding Two Different Datatypes

It is often observed that when one tries to add two integers, they get their desired output, and when they try to add two different data types, they get an error. 

But in JavaScript, it does not work like this; when you try to add two integers, you get the sum. But when you add two data types, like a number and a string, they concatenate instead of showing the error.

Let's check out some examples to get this clear.

Example

What should be the output of the following code?

let x =1;
let y = 1;
console.log(x+y)


The output gives 2, which is correct.

output

But what should be the output of this:

let x = “hello”
let y = 21
console.log(x+y)

 

It gives hello21 as the output.

output

Explanation: 

Here as you can see, in the two cases, we have two integers, and their sum gives us the result or the answer. But as you can see in the third case, we have a string “hello”  and an integer 21, so on adding them, we get a string concatenation of “hello21”

So basically, what JavaScript does is, when it encounters two different data types, it converts them all into string data types and then performs simple string concatenation.

Floats Misunderstood

The numbers in JavaScript are stored as 64-bit floating-point numbers or floats. So when we try to add two numbers or floats, we experience difficulties in the precision of the result. 

Example

let x = 0.1;
let y = 0.2; 
console.log(x+y)

 

What should be the output of this? 0.3?

No, the correct answer is 0.30000000000000004, as shown below.

output

Explanation: 

As discussed above, this happens because of floating point numbers.

To get the desired output, we can multiply the variables by 10 and then divide it by 10. After doing this, you’ll get the desired result.

For example:

console.log((x*10 + y*10)/10)

 

output

Loose Comparison

This is the most common mistake people need to correct when using JavaScript. When anyone wants to compare two variables and check if they are equal, they use the == sign to compare them. 

But sometimes, this may result in some unexpected errors, so one should try

to compare using the === sign to suppress those errors. 

Example

let x = “hello”;
let y = “hello”;
console.log(x == y)

 

output

As you can see, by comparing the two variables, we get the desired result.

But here’s the catch. What should be the output for this?
 

let x = 1;
let y = “1”;
console.log(x == y);

 

output

As you can see, it gives us true.

Explanation:

In the above example, it compares only the value of the two variables around the == sign and not the data types. So the value being 1 on both sides gave true.

Hence one should use === instead of ==,  as === compares both the values and the data types of the items to be compared. Let’s take an example for a better understanding.

console.log( 1 === “1” )

 

output

Undefined vs Null

What do words like undefined and null mean to you? Do they look the same to you?

If yes, then there are others to say this. Many think they are the same or similar, but that is not the case.

They are undoubtedly different and have different meanings. Let's try to understand the difference between them.

Undefined is the type where the variable is declared but is not assigned any value. It has its own data type.

Null represents the absence of any object value. The variable/object/attribute is not even declared in this case. It is of the object type.

Example

Try running

undefined === null

 

What should be the output?

output

Explanation:

Let’s look into both types using typeof.

console.log(typeof(undefined))
console.log(typeof(null))

 

output

As you can see, the type of undefined is undefined, but the type of null is an object, and so on comparing gives False.

Hence, undefined and null are not the same and hold different meanings.

Variable Scope Misunderstood

Variable Scope means the scope in which the variable is defined. Usually, the variable is defined inside a scope, where it can be called/used, etc. But in the case of JavaScript, this is not the case. More specifically, this is certainly not the case with var declarations.

Variables declared with let and const follow the scope rule, but variables declared with var are defined in the entire function scope.

Example:

for (let i = 0; i < 1; i ++){
    var hi = “hello”
}
console.log(hi)

 

What should be the output?

It should give ReferenceError : hi is not defined, as it is defined inside the for loop and is accessed outside the loop.

But we get hello as the output.

output

Explanation

The variables declared via the var declarations are either globally scoped or functionally scoped and not block scope, so they can be updated / re-declared in their scope. 

output

 

Variables declared via let and const are block-scoped and so are defined only for their specific block.

Callbacks are not Synchronous

Many new developers are under the impression that the callbacks are synchronous, so they are first called, and then the rest of the code is run.

Those who are not familiar with what are synchronous and asynchronous functions can read this article for clarification.

In a synchronous function, the statements are executed sequentially (step by step), and the code is run in a manner that it is written with.

Example

Here is an example of a synchronous function

let h = “hello”
function sayHI(){
	console.log(“function called”)
}
console.log(h)
sayHI()

 

What should be the output?

Yes, you guessed it correctly, it should be hello first and then function called.

output

But what if the function is passed as a parameter to setTimeout function? If you are not familiar with setTimeout function, you can refer to this blog.

function callBack(){
	console.log(“i’m callback”)
}
setTimeOut(callback,5000);
console.log(“I’m last”)

 

What should be the output of this code?

output

As you can see, the output is in reverse order. The console.log statement after the setTimeout gets called first and then the callback function.

Explanation:

This happens because callbacks are asynchronous. So here, after reading the statement sequentially, we encountered a setTimeout function. Since this is asynchronous, it gets stored in a stack, and we move forward with the code. Once the duration (30 seconds for this case) is over, then the function is called and popped from the stack. 

We return to the function declaration and run the function body, and after this, we continue with the line of code where we initially popped and called before this callback.

{} === {} is True or False?

As the name suggests, what should be the output for the following code, according to you

console.log( {} === {} )

 

If your guess is True, then I’m sorry to disappoint you, but the actual answer is False.

Example 

output

Let’s look into another example to get a better understanding.

What should be the output for this code?

let obj1 = {"name": "Karan", "age" : 17}
let obj2 = obj1
obj2.name = "Manav"
console.log( obj1 )

 

output

Explanation

So what is happening here is the objects are passed by reference instead of values.

So when we reassign the obj2 = obj1, instead of making a copy, they both refer to the same JavaScript object.

Explanation

Hence by changing one object’s attribute, we are changing the entire object’s property, as they both are pointing to the same object.

Hence on comparing {} === {}, we get False as it compares the reference rather than the value and datatype of the objects. 

Breaking A Return Statement

We know that semi-colon (;) is not of much importance in JavaScript, but it does ensure that the line of code has ended. So if we do not put a semicolon at the end of a line and write the next line, the browser considers the next line as the continuation of the previous line. 

Let us look at some examples to get a better understanding.

Example 

What should be the output of these two codes? Will it be the same or different?

function call () {
	let x = 1
	return 10 * x
}
console.log(call())

 

output

and 

function call () {
let x = 1;
return 10 * x;
}
console.log(call());

 

output

They both output the same number i.e 10, as they are the same code, one with a semi-colon and one without a semi-colon.

But now what happens?

function call () {
	let 
	x = 1
	return 10 * x
}
console.log(call())

 

output

The output should remain the same, as JavaScript allows the breaking of lines, So it basically converts the above code to 

function call () {
	let 
	x = 1;
	return 10 * x;
}
console.log(call());

 

So as you can see, the semicolon (;) added after the variable declaration means that JavaScript interprets it in this way, that the two lines are a continuation of each other, and so the semicolon is placed afterward.

But if the breaking happens after a return keyword

function call () {
	let x = 1
	return
	10 * x
}
console.log(call())

 

Now the output becomes undefined

output

This happened because JavaScript interpreted this as

function call () {
	let x = 1;
	return;
	10 * x;
}
console.log(call());

 

and so when it encounters the return; statement, it returns from the function without going further into the function definition, and so we get undefined.

Good Practices to Adopt

Now let’s discuss some good practices to adopt while writing JavaScript.

Avoid Global Variables

Always try to minimize the usage of global variables, as they can be redefined inside any function or scope, and the value can be altered or changed. 

If you have a large codebase, keeping track of the location where the variable was changed can be difficult.

Example

let x = 100;
function hello (){
	x = 12
}
hello()
console.log( x )

 

This results in 12 instead of 100, and so the value of x is changed.

output

Explanation

The value of gets redefined when the function is called, and so the output shows the updated value of x after the function call.

So instead of declaring global variables, we should always declare local variables, whose scope is limited to the block. 

Initializing Variables

Always initialize the variables with some initial values. This helps the developers and reviewers understand the code and the primary function of that variable. 

This improves code readability, as well as code functionality. 

Example

let x = 1
let name = “ “
let obj = { }
let arr = [ ] 

 

Try to initialize all the variables in one place rather than initializing them at their time of usage. Declaring at one place makes code clean and organized. 

Stay Alert for Type Conversion 

As you know, variables in JavaScript can take any datatype, as there is no strict datatype declaration at the initialization time. 

Variables can be of any type, as they are defined with the keywords let and const so that they can be integers, strings, objects, arrays. etc

 

Example 

let x = "hello"
console.log(x)

x = 12
console.log( x )
The output gives 12

 

Explanation 

As JavaScript is loosely typed, all the variables and their declarations can be of any data type. Developers should take care of the types defined and should obey the structure and nomenclature defined above. 

 

output

Avoid Declaring Strings or Arrays as Objects

Always avoid declaring numbers, strings, or arrays as objects. The new keyword is used to create Objects and should be avoided.

Declaring them as JS objects not only reduces computation speed but also produces ugly side effects.

Example

WRONG WAY:

output

 

RIGHT WAY:

output

 

Declaring strings, numbers, and arrays as primitive types are preferred. 

Note: Declaring as an object also results in false results and anomalies while comparing strings.

console.log( new String(“hi”) == new String(“hi”) )
output

This gives False, as we are comparing JS Objects, and as discussed above, they are checked via reference and not by values.

Must Read Fibonacci Series in JavaScript

Frequently Asked Questions

How are new objects created in JavaScript?

To create a new JavaScript object by value, use the spread operator to make a copy of the object and store it in a new variable.

What is the variable naming convention followed in JavaScript?

JavaScript follows the TitleCase naming convention, where the first letters of every new word are capitalized. It is encouraged that developers/users should follow this naming convention.

When to use var, let, and const?

After ES6 releases, it is encouraged that one should use let and const, as they are block-scoped and not function-scoped. Now, developers have stopped using var due to anomalies and are using let and const.

What is NodeJS?

NodeJs is JavaScript runtime environment that runs inside a terminal rather than a browser window. It was specifically designed for developers to test their code on their machine rather than the browser's console. It helps to execute JavaScript code outside the browser.

What are some most common mistakes one makes while writing code?

Common JavaScript mistakes include missing semicolons, confusion between assignment and comparison operators, loose comparisons, confusion between addition and concatenation, working with floats, etc.

Conclusion

So Ninjas, as we discussed, these are some of the common mistakes that people make while writing JavaScript code. After reading this article, I'm sure you won't be making the same mistakes again or will be aware of the errors.

If you find this helpful in any manner, please look into more of our content

 

If you want to study more about JavaScript and practice the questions that require you to take your basic knowledge on these topics higher, you can visit Coding Ninjas Studio. Try our Basics of JavaScript Courses to be more confident in JavaScript. Until then, All the best for your future endeavors, and Keep Coding.

Previous article
Best Practice in JavaScript
Next article
Arrays in JavaScript
Live masterclass