10 Useful javascript tips and practices that you may want to start applying in your projects

10 Useful javascript tips and practices that you may want to start applying in your projects

If you are a JS developer with experience, probably you'll find that some of these tips are really trivial. However, for a javascript beginner, these tips will be really important and useful if you want to improve your development skills with this language.

Notable JavaScript masters and developers have been using many of these techniques to write powerful, efficient JavaScript, and now you'll learn how too.

10. Scripts only in external files

Cache files on the user device is better than make a new request everytime. Everytime an user gets into a website, the template (i.e a blog) is always different as the blogger creates a new entry everytime he wants. Therefore the template is not cached, therefore if your scripts are written directly in the document and they're not referenced in a script tag, it will be requested everytime the user visits the webpage.

If your script in the document is big (more than 30 lines), you should be think it in moving it into a external script :

<div>
 Bla bla bla ...
</div>
<script>
 //
 // More than 30 lines of Javascript in the Document
 // that you can move to an external file
 //
</script>
<!-- Reference it better in a external script -->
<script src="my/path/tomyscript.js"></script>

If you can move your js code into a script file , do it always when you are able to.

9. Know when compare with equal or identical

The == (or !=) comparator performs an automatic type conversion if needed. The === (or !==) operator will not perform any conversion. It compares the value and the type, which could be considered faster (jsPref) than ==.

[20] ==  20      //  true
[20] === 20      //  false

'45' ==  45      // true
'45' === 45      //  false

 []  ==  0       //  true
 []  === 0       //  false

 ''  ==  false   //  true but [true == "a"]  false
 ''  === false   //  false 

== Double equals (aka loose equality) will not compare the type, however it will typecast values being compared within the statement. This is called type coercion and it is regarded as an evil operation.

=== Triple equals (aka strict equality) will compare the type, but will not typecast the values meaning they are compared as is without being transformed. Because there is no type coercion, the triple equals is faster and the recommended approach for comparing all kinds of values. This means both types need to be the same for the condition to equal true.

Use == (or !=) only if you check for null or undefined.

8. Be careful with the string concatenation

You need to be sure of the type of your variables during the concatenation.

Analyze the following example :

var a = 1;// Int
var b = 2;// Int
var c = '3'; // String
var d = " my Number"; // String

console.log(a + b + c + d);
// Output : 33 my Number
// But expected other thing ...

To avoid unexpected behaviours, convert it to string, use the concat method or concatenate them with pluses but set the first variable in the line as string :

var a = 1;// Int
var b = 2;// Int
var c = '3'; // String
var d = " my Number"; // String

console.log("" + a + b + c + d);
console.log(a.toString() + b.toString() + c.toString() + d);
console.log(''.concat(a, b, c, d));
// All of them output : 123 my Number

7. Re-declare variable in 1 line

Instead of use the following syntax that occupies more than 3 lines checking if it exists with if statements :

Note: although verify using the ! operator already is short, using the short-circuiting declaration is even shorter.

var myInitialString = "";

function concatenate(parameter){
    // Check if variable exists
    // or 
    // typeof(parameter) == "undefined"
    if(!parameter){
        parameter = "A previously default value";
    }
    
    return myInitialString + parameter;
}

Use the short-circuiting declaration instead:

var myInitialString = "";

function concatenate(parameter){
    // Re-declare with 1 line instead
    parameter = parameter || "Use this value instead if parameter doesn't exists";
    
    return myInitialString + parameter;
}

As you know, everything in Javascript is truthy or falsy, falsy JavaScript values include:

  • false.
  • 0.
  • empty strings ('' or "").
  • null.
  • undefined.
  • NaN (NotANumber).

The || operator first evaluates the expression on the left, if it is truthy, it returns that value. If it is falsy, it evaluates and returns the value of the right operand (the expression on the right).

6. If statements shortener

Keep using the short-circuiting declaration to make your if's statements even shortener than they are. If a statement of this class returns a boolean value, you can return the evaluation of the if statement instead (which returns a boolean value).

function isAdult(age){
    // if age parameters exists and its value is greater than 17..
    if(age && age > 17){
        return true;
    }

    return false;
}

A boolean will be returned from the following evaluation too :

function isAdult(age){
    // If age parameter doesn't exists, falsy is returned
    // and if the parameters exists and is greater than 17 truthy is returned
    return age && age > 17;
}

And you can create short if statements not only for return values, create more fancy code combining && and || comparators with short-circuiting declaration style :

// Execute a request to the server if the token is valid, otherwise refresh it
if (tokenIsValid(token)) {
    executeRequest(token);
}else{
    refreshToken();
}


// If token is valid is truthy, then the executeRequest will be executed too.
// otherwise the refreshToken will be executed.
tokenIsValid(token) && executeRequest(token) || refreshToken();

One line code, clean and readable (questionable) isn't?.

5. Don't be scared of the bitwise Not operator (~ or ~~), it doesn't bites

If you see this operator in third party code and you don't know what it means, don't be afraid it is not common, but is not from another world.

The single use of ~ has a special effect when using with integers, explaining the effect of this symbol is like use the following function :

function bitwiseOperator(value){
  var result = Math.floor(value);
  // return the negative value of the result + 1;
  return - (result+ 1);
}

It just return the negative value of the addition of 1 to the number. A well known use , is to check if an array has an item with indexOf function instead of differentiate with -1, make the evaluation as truthy or falsy :

// true
var hasItemTwo = ~[1,2,3].indexOf(2);

if (hasItemTwo) {
    console.log("The array contains 2");
}

// instead of 

if([1,2,3].indexOf(2) != -1){
    console.log("The array contains 2");
}

Didn't get it? don't panic ! if you want more information about this operator, read this article.

Use double bitwise NOT when:

1. You want to convert the number from float to integer.
2. You want to perform same operation as Math.floor() but a lot quicker.
3. You want to minimalize your code.

Do not use double bitwise NOT when:

1. You run Google Chrome (apparently?).
2. You care about readability of your code.

4. Combining data from 2 arrays correctly

You need to know when use loops and when not. For combine 2 arrays, you don't need to loop over the second array and push every single item into the first array as shown in the following (bad practice) example:

var firstArr = ["12",{myObject:12},123,"Hi","Test"];
var secondArr = [9,5,23,12,"Hello","Second test"];

for(var i = 0;i < secondArr.length;i++){
    var item = secondArr[i];
    // add item to second array
    firstArr.push(item);
}

console.log(firstArr);

// outputs : 
// ["12",{myObject:12},123,"Hi","Test",9,5,23,12,"Hello","Second test"]

Although it works, it is not the best way to do it, combine them without using a loop.

var firstArr = ["12",{myObject:12},123,"Hi","Test"];
var secondArr = [9,5,23,12,"Hello","Second test"];

// Combine arrays
Array.prototype.push.apply(firstArr,secondArr);

console.log(firstArr);

// outputs : 
// ["12",{myObject:12},123,"Hi","Test",9,5,23,12,"Hello","Second test"]

If you don't know the difference between .call and .apply property of a function, you may want to read this article otherwise you'll get lost in how this practice works. In this case we use the .apply property to change the this context of the push method as the first array, as you know, the .push method add all the arguments that it receives to the given array, for example:

var myEmptyArr = [];

myEmptyArr.push(1,2,3,4,5);

console.log(myEmptyArr);
// [1,2,3,4,5]

Therefore, the items of the second parameter (the second array) will be taken as arguments and will be appended to the first array thanks to the apply function. Easier to write than a loop isn't?

3. Switch vs if

The classic question of whether to use a switch statement or a series of if and else statements is not unique to JavaScript and has spurred discussions in nearly every programming language that has these constructs. The real issue is not between individual statements, of course, but rather relates to the speed with which each is able to handle a range of conditional statements.

Analyze the following if example : 

// the variables : result doesn't exists
function example(value){
    if (value < 6){
        if (value < 3){
            if (value == 0){
                return result0;
            } else if (value == 1){
                return result1;
            } else {
                return result2;
            }
        } else {
            if (value == 3){
                return result3;
            } else if (value == 4){
                return result4;
            } else {
                return result5;
            }
        }
    } else {
        if (value < 8){
            if (value == 6){
                return result6;
            } else {
                return result7;
            }
        } else {
            if (value == 8){
                return result8;
            } else if (value == 9){
                return result9;
            } else {
                return result10;
            }
        }
    }
}

example(5);

And now the same code written with switch statement, the switch statement simplifies both the appearance and the performance of multiple conditions :

function example(value){
    switch(value){
        case 0:
            return result0;
        case 1:
            return result1;
        case 2:
            return result2;
        case 3:
            return result3;
        case 4:
            return result4;
        case 5:
            return result5;
        case 6:
            return result6;
        case 7:
            return result7;
        case 8:
            return result8;
        case 9:
            return result9;
        default:
            return result10;
    }
}

example(10);

Which would you choose?.

In JavaScript, if statements are generally faster than switch statements when there are just one or two conditions to be evaluated. When there are more than two conditions, and the conditions are simple (not ranges), the switch statement tends to be faster. This is because the amount of time it takes to execute a single condition in a switch statement is often less than it takes to execute a single condition in an if statement, making the switch statement optimal only when there are a larger number of conditions.

2. Measure performance and solve performance issues

Yes captain obvious !

Captain obvious

Nobody likes slow websites or slow applications, be sure to test all your heavy functions and analyze the points where it can be optimized.

You can read a detailed article of how to measure performance of your functions with Javascript using Benchmarks or using the Chrome developer tools here.

1. Keep safe your code with closures

Wrap your code in anonymous functions to prevent problems in your own code. Almost every website uses different scripts from different sources. By default, any function or variable created on the page is defined within the global "scope". This could become a serious problem if two scripts were using the same exact variable/function names.

var myName = 12;

(function(){
    var myName = 123123123123;

    // 123123123123
    console.log(myName);
})();

// 12
console.log(myName);

As you can see, the closure is respected and the myName variable still has 12 value in its context as the myName inside the wrapper belongs to another context. That's the point of use closures.

If you know another awesome tip to share with the community, don't be shy and share it with us in the comment box ! Have fun

Become a more social person