Top 10 Javascript tips

Don’t forget "var"

When you assign a variable’s value for the first time, always make sure you're not doing it to an undeclared variable. Assignment to an undeclared variable automatically results in a global variable being created. Avoid global variables ❌ Global variables are easily overwritten by other scripts. For example, if two separate parts of an application define global variables with the same name but with different purposes, it can result in unpredicted errors and it will be a horrible experience to debug such a problem. Generally, you should try to scope your code so that you need as little as possible in the global scope. The more global variables you use in your script, the less is the chance that you can use it alongside another script. Normally variables in a function should be local so that they go away when you exit the function.


"By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries." - Douglas Crockford

Delete vs Splice

Use splice instead of using delete to remove an item from an array. Using delete will remove the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined.

map vs for loop

Use the map() function method to loop through an array’s items

var squares = [1,2,3,4].map(function (val) {  
    return val * val;  
}); 

// squares will be equal to [1, 4, 9, 16]

Immutability — The original array will be unaffected. This has potential benefits in cases where the original array is still needed elsewhere. For loops can also be written so as not to update the original array, but it requires more code and updating our new array as part of our loop operation. On the other hand map() keeps this cleaner since you only have to work in one scope to still maintain immutability Cleaner code — When doing identical things, map can almost always be written with less code than for. It can be clearly written on one line sometimes whereas for requires at least two or generally three with braces included. Also, scope isolation and a reduction in the number of variables you need alongside reduced size all make code objectively cleaner.

Rounding numbers

The toFixed() method converts a number rounding to a specified number of decimals.

var pi =3.1415;
pi = pi.toFixed(2);  // pi will be equal to 3.14


NOTE :  toFixed() returns a string and not a number.

Use console.table

You can use console.table to show objects in tabular format:

table=[{state: "Texas"},{state: "New York"},{state: "Chicago"}]
console.table(table)

Avoid using try-catch inside a loop

The try-catch construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable.

var object = ['foo', 'bar'], i;  
for (i = 0, len = object.length; i <len; i++) {  
    try {  
        // do something that throws an exception 
    }  
    catch (e) {   
        // handle exception  
    } 
}

to ⬇

var object = ['foo', 'bar'], i;  
try { 
    for (i = 0, len = object.length; i <len; i++) {  
        // do something that throws an exception 
    } 
} 
catch (e) {   
    // handle exception  
}

When an error occurs, the first one lets you continue the loop while the second one exits the loop. The first one is suited if an exception thrown by your code is not severe enough to halt your entire program.

The Best Way to Convert Your Values in Numbers to Strings

Converting to a string is another type conversion. Here’s how you convert your values in numbers to strings: {% code-block language="js" %}const value = 1 + "";   console.log("Value ofter converting to string: "+value);   console.log("Type of value is: ", typeof value);{% code-block-end %} Here we used the concatenation operator “+”. We could have used an empty set of double-quotes as well. But with the concatenation operator, our number transformed into a string very quickly.‍

Start to Use Functional Inheritance

JavaScript makes use of prototypal inheritance whereby objects inherit from other objects. This is interesting and simplifies many things. The class operator also comes bundled with the language with ES6. But the fact remains the same that it is overly complex compared to functional inheritance. Even though many Node experts prefer the simplicity of the latter. It can be implemented by a simple function factory pattern. It does NOT require the use of prototype, new or this. Also, there are no implicit effects when you update the prototype which causes all the instances to change as well. This is because in functional inheritance each object makes use of its own copy of methods. Here is a code from TJ Holowaychuk, the genius behind Express, Mocha, Connect, and dozens of other Node modules. The source code describes the uses of functional inheritance. You can check out the full source code here. Many developers aren’t aware that they should not be checking their node_modules folder. Many learn this the hard way. In fact, there is no reason for you to check this folder. Think of a scenario where someone checks your source out and at the same time run npm install and download all the modules required. You may think, it’s not a big deal if you check in node_modules or anyone else does. That’s because from the surface nothing may appear wrong. But if the person checking out your source is on a different operating system (other than yours) and at the same time one of the modules that your app uses gets compiled when it’s installed via npm, the app will crash. This happens because the modules like bcrypt and sentimental are compiled on the host system because they have native components written in C. The best way to avoid this situation is to completely avoid checking the node_modules folder.

Dojo ShrinkSafe

ShrinkSafe uses the rhino library to parse your code and produce compressed versions of JavaScript files that you can drop directly into your webpages.

Multiple condition checking

For multiple value matching, we can put all values in an array and use indexOf() or includes() method.

if (value === 1 || value === 'one' || value === 2 || value === 'two') { 

}

to ⬇