JavaScript

Combine all variable declarations

It is common to see code where all variables are declared separately in JavaScript. When in a scope, or a function, we have tendency to declare variables in multiple places thinking they are isolated from one another. Here is an example:

function getSelectedElements() {
    var allElements = document.getElementsByTagName("*");
    var className = "js-selected";
    var filteredElements = [];

    for (var i = 0; i < allElements.length; i++){
        var currentElement = allElements[i];
        var currentClass = currentElement.className;
        if (currentClass === className) {
            filteredElements.push(currentElement);
        }
    }
    return filteredElements;
}

In this function we have the impression that currentElement, currentClass, and i only exist inside the for loop. What happens in the background is those declarations are hoisted up in the function and all exist in the same scope as the other variables in the function. To make things clear, we can combine all the variable declaration to the top of the function. Note that it is not necessary to use the var keyword every time we declare a variable, we can just separate them with a comma.

// Improved function.
function getSelectedElements() {
    var allElements = document.getElementsByTagName("*"),
        className = "js-selected",
        filteredElements = [],
        i,
        l = allElements.length,
        currentElement,
        currentClass;

    for (i = 0; i < l; i++){
        currentElement = allElements[i];
        currentClass = currentElement.className;
        if (currentClass === className) {
            filteredElements.push(currentElement);
        }
    }
    return filteredElements;
}

Even though JavaScript is a loosely typed language, nothing stops you from declaring your variables before using them. It is just much easier to read and scale.

See For loop does not create a scope for more info on scope-less functions.


Comments

Let's hear your thoughts

For my eyes only

There are no comments added yet.