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.
Javascriptis 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?
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)
You can also try this code with Online Javascript Compiler
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)
You can also try this code with Online Javascript Compiler
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)
You can also try this code with Online Javascript Compiler
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” )
You can also try this code with Online Javascript Compiler
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)
You can also try this code with Online Javascript Compiler
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.
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.
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()
You can also try this code with Online Javascript Compiler
Yes, you guessed it correctly, it should be hello first and then function called.
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”)
You can also try this code with Online Javascript Compiler
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( {} === {} )
You can also try this code with Online Javascript Compiler
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.
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())
You can also try this code with Online Javascript Compiler
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())
You can also try this code with Online Javascript Compiler
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 )
You can also try this code with Online Javascript Compiler
This results in 12 instead of 100, and so the value of x is changed.
Explanation
The value of x 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 = [ ]
You can also try this code with Online Javascript Compiler
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
You can also try this code with Online Javascript Compiler
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.
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:
RIGHT WAY:
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”) )
You can also try this code with Online Javascript Compiler
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.