DEV Community

Neha Sharma
Neha Sharma

Posted on • Updated on • Originally published at hellonehha.hashnode.dev

Improve your JavaScript code with these...

Have you ever thought what are the areas or things to take care of to improve your code? Logical code can be improved by focusing on time and space complexity.

Alt Text

However, the way we are writing the code also contributes a lot. Below are a few tips for you.

1. use const

Use const in your JavaScript code for the variables and methods. This will help you in avoiding the unexpected change in the value or reassignment of the variables.

An easy way to make your JavaScript code safe from bugs.

const name = 'Delhi';
const getName = function(){
    name = 'Mumbai'; // this will throw an error
    return name;
}

getName();

Enter fullscreen mode Exit fullscreen mode

2. Avoid global variables and methods

As we saw that const won't let the accidental value update. There are hardly any programs that can be done using only const. We need to declare the variables, & methods.

So, in such a case, we use var or let but instead of making them global, we should make their scope as per the requirements. Why? global variables could be error-prone. declare global only when it is unavoidable and required.

So, in short, avoid the global variables and methods.

3. functions /methods

Always create the functions to wrap your code or logic.

Eg: Instead of doing this:

var a = 2;
var b = 3;

var result = a + b;
return result;

Enter fullscreen mode Exit fullscreen mode

Do this:


function sumNumbers(a,b){
     return result = a + b;
}

sumNumbers(2,3);

Enter fullscreen mode Exit fullscreen mode

4. Array new methods

The ECMA team is doing an amazing job in making the developer's life easy and difficult at the same time. How? well, they are coming up with awesome features to make our life easy but at the same time there is always something new is coming up :)

ES6 introduced a lot of array-based methods. such as map(), reduce(), filter(), every(), some(). They (map()) implicitly return a new array. Do you know what it means?

It means that they (map()) are efficient than the code we will write to do the same operation.

What about the rest of the methods? Well, again they are helping us to reduce the number of line of code we are writing eg: filter(), or reduce(): if you will write the code of these by yourself (kind if polyfill) you will see the amount of code we have to write.

So, wherever you get the chance use these methods.

Eg: Instead of this:

const a = [1,2,3,4]
let tempArr = [];

for(let i =0; i < a.length; i++){ 
  tempArr.push(a[i]);
}

return tempArr;

Enter fullscreen mode Exit fullscreen mode

Do this:

const a = [1,2,3,4];

const b = a.map((val, index) => {
  return val;
});

return b;

Enter fullscreen mode Exit fullscreen mode

You can follow me at Twitter, Linkedin;


5. Patterns are your friends

Patterns help in readability, and encapsulation. In JavaScript, we have different kinds of patterns and as per the need, we can pick the pattern. It is a good practice to identify or move your code to a pattern.

Read about patterns here

6. Communication through Comments

Write meaningful comments. Comments are the way the developers communicate and understand the code. It is important to use clear and well-written comments in the code.
One of the areas I would strongly suggest having comments is: what kind of arguments a function is expecting. This is important when we are not using any type-checking library.

Instead of doing this:

/* pass value to add numbers  */

Enter fullscreen mode Exit fullscreen mode

Do this:

/**
 * return the sum of the two given arguments
 * @type numbers
 */

Enter fullscreen mode Exit fullscreen mode

7. Identify Reusable Code

Every programming language focus on the 'DRY - Do not Repeat Yourself' or the Reusability principle. JavaScript also focuses on the same. As a developer identify the reusable code and move them to functions. So, that it can be reuse, test once, avoid errors, save time, and have consistency.

8. Error and exception handling

Use try/catch to handle the error and exceptions. This is one thing that a lot of developers just missed (including me). Using try/catch is an important way to avoid the embarrassing errors messages on browsers.

9. Use Pure functions

Pure functions are important to avoid errors and writing functional, reusable code.
Pure functions mean it will always return the same output with the same input values without any side effects. Eg: map() is an example of the pure function but Math.random() is not.

Why pure functions are important?
As I mentioned that they help in avoiding errors, promote reusable and functional code.
When there are no side effects there will be fewer errors. They are the small functions that promote reusability. Hence, helps us in writing reusable code.


These are a few points but are not limited to. We should also take care of the performance, data operation's complexity, and a lot more. Always keep questioning and refactoring your code. There might not be a perfect code but we should not ship bad code ever.

Happy Learning!!

Top comments (5)

Collapse
 
gsonderby profile image
Gert Sønderby

At the risk of asking a stupid question, in what way does Math.max(x, y); violate function purity? I cannot for the life of me think of a case.

Collapse
 
psiho profile image
Mirko Vukušić • Edited

I don't think it's true that .map() and similar are faster than "traditional" loops. It's just more readable. However, difference is insignificant most of the time. But if you have a realy large array that you're iterating over, then do it un for loop.

As for comments... It's subjective, but I like "clean code" virw on this and like the code that does not need comments at all. So write descriptive variable/function names, break functionality in smaller parts, use readable code and avoid comments unless neccessary.

EDIT: to be more precise, map() was just an example but I was referring to all "new features to make our life easier". So in general, traditional loops are faster, but of course not always, faster than filter(), foreach(), etc. Not for your exact use case above. In example check: jsbench.me/5fizlui8g7

Collapse
 
decpk profile image
Praveen kumar

They implicitly return a new array. This is not true for all the methods that you have mentioned. Only map, filter will return brand new array. But reduce you can get a single value, It can be an array also. But some and every returns boolean value.

Collapse
 
jcbbb profile image
jcbbb

What do you mean they are more efficient because they implicitly return a new array?
Your 3rd example even has a syntax error. Learn something before making a post, otherwise this is just embarrasing.

Collapse
 
hellonehha profile image
Neha Sharma

I would have appreciated your comment if you could have pointed out nicely - that there is a syntax error. But you cross the line of commenting properly - I would suggest learn how to comment nicely otherwise it is also embarrassing to read your rude comment.