Monday, September 29, 2014

The Single Var Pattern in JavaScript - Six Revisions

The Single Var Pattern in JavaScript - Six Revisions


The Single Var Pattern in JavaScript

Posted: 29 Sep 2014 03:00 AM PDT

One of the most beautiful things about JavaScript is its flexibility. The language gives developers a lot of slack by not giving us a lot of rules and conventions to deal with.

A prime example: JavaScript allows us to create any type of variable, anywhere in our script (because it’s a dynamic programming language). That’s great news, but it can also be a double-edged sword if we don’t exercise a bit of caution.

One popular way of working with JavaScript variables more effectively is the single var pattern.

I first formally encountered this pattern in Stoyan Stefanov’s book, JavaScript Patterns, and I’ve been using it ever since.

Douglas Crockford, a leader in the world of JavaScript, supports the single var pattern. His reasoning is below:

[...] because JavaScript does not have block scope, it is wiser to declare all of a function’s variables at the top of the function. It is recommended that a single var statement be used per function.

JSLint: The JavaScript Code Quality Tool

Let’s talk about the JavaScript pattern and why you might want to use it in your development projects.

The Single Var Pattern

In the single var pattern, all local variables are created using only one var statement. The statement is placed at the start of the function block. Each variable is separated by a comma (,), and the last variable ends with a semicolon (;) which terminates the var statement.

Here’s an example of the pattern:

function myfunction() {    var  a = 1,         b = "Hello",         c = { name: "Jake", age: 64 },         d = new Date(),         e;  }

Details

The above example is equal to having multiple var statements for each variable:

function myfunction() {    var a = 1;    var b = "Hello";    var c = { name: "John", age: 64 };    var d = new Date();    var e;  }

By the way, the multiple var statement pattern shown above is a good alternative to the single var pattern because the variables are also declared at the start of the function block (which avoids logical errors) and is also readable, thus providing web developers the same benefits, albeit in a more verbose manner.

In JavaScript, spaces, newlines, tabs, and other spacing characters before and after commas and semicolons are ignored, so we could have written the example above in just one line, like so:

function myfunction() {    var a = 1, b = "Hello", c = { name: "John", age: 64 }, d = new Date(), e;  }

But it’s a good practice to put each variable on its own line for improved readability, and so that you can more comfortably comment your variables individually if needed.

Does Data Type Matter?

JavaScript is a dynamically typed language, so we don’t need to explicitly declare what data type a variable is/will be. The data type can also be changed from one type to another without any special treatment. So, we can have a mixture of data types — strings, function literals, arrays, undefined, etc. — in one var statement without any issues.

Do Some Work

The book I mentioned earlier also recommends doing some "actual work" during the single var statement. For example, let’s say we created a function that returns a randomly picked integer number between two numerical arguments we feed it:

// A function that returns a random integer number  // between two specified integer arguments.  var randomizer = function (a, b) {    var min = a,        max = b,        random = Math.random(),        result;      // Calculate random number    result = Math.floor(random * (max - min) + min);      return result;  }  // Display random number in an alert box  alert(randomizer(1, 100));

What we could do instead is to include the calculation of the result variable’s value in our single var statement, as follows:

// A function that returns a random integer number  // between two specified integer arguments.  var randomizer = function (a, b) {    var min = a,        max = b,        random = Math.random(),        // Calculate random number        result = Math.floor(random * (max - min) + min);      return result;  }  // Display random number in an alert box  alert(randomizer(1, 100));

Doing some work during the single var statement does two things:

  • It slightly reduces the amount of code we have to write
  • It avoids redundancy. More specifically, we don’t need to declare an undefined/empty variable that we will end up using in our function anyways

A Variation

There’s an alternative formatting style for the single var pattern, which is to place the comma-separators at the start of each line, instead of at the end:

function myfunction() {    var   a = 1        , b = "Hello"        , c = { name: "John", age: 64 }        , d = new Date()        , e;  }

The purpose of this variation is to remind you to separate your variables with commas whenever you add a variable in the statement.

The placement of the commas is a matter of preference. Me? I like having the commas at the end of the line because it makes the var statement easier to read, and my code editor’s syntax highlighter quickly reminds me that I’m missing a comma between variable declarations. Also, in my opinion, having a line start with commas is unnatural and less readable. To each his/her own.

Benefits of Using the Single Var Pattern

Why would you want to use this JavaScript pattern? I’ll give you three reasons. But before I discuss them, I also want to say that there’s no "one correct way" of declaring JavaScript variables because the language doesn’t have any enforced rule or explicit standard for this process. Other ways, such as the multi var pattern I briefly mentioned earlier or even just declaring variables on first-use will work just fine. With that said, you do get a few benefits from applying the single var pattern.

Ease of Use

It’s easier to create and manage variables when they are all in one spot. You don’t have to wonder where a certain variable is; all you have to do is scroll up to the top of the function to review or modify your function’s variables.

Code Readability

The single var JavaScript pattern is similar to the abstract of a scientific paper: It provides the reader with a quick overview of what the function will do without having to read the entire thing, compared to if the variables were declared on first-use. However, this is only going to be true if the variables are named intuitively and when the function is commented well.

Reduce the Possibility of Logical Errors

Because all of the variables are right at the start of the function block, we can sidestep issues related to variable hoisting, naming collisions, and accidentally declaring global variables. Let’s talk about each of these real quickly.

Hoisting

In JavaScript, hoisting refers to the language’s behavior of processing all of the statements first before it executes anything else. In other words, JavaScript hoists them up to the top of the scope. Because we’re deliberately and consistently placing all of our variables at the beginning of the function, it helps us avoid unforeseen results related hoisting.

Variable Naming Collisions

When you’re working on long and complex scripts, you might, at some point, unintentionally reuse a variable name, and this can lead to logical errors. By having all your variables in one spot, you can keep an eye out on what variable names you have already employed.

Helps Minimize Global Variables

It’s a good practice to eliminate any unnecessary global variables in your work because you might run into naming collisions with other JavaScript libraries you might be using that are relying on global variables. Also, whenever you can, you should use local variables because it’s faster to access compared to global variables. The single var pattern makes it more convenient to create local variables and serves as a constant reminder to watch out for accidental global variables.

Single Var Pattern Downsides

To get a well-balanced perspective, I recommend reading the following articles to learn about the disadvantages of the single var pattern; they have strong arguments that can help you make an informed decision.

Related Content

About the Author

Jacob Gube is the founder of Six Revisions. He’s a front-end web developer by profession. If you’d like to connect with him, head on over to the contact page or follow him on Twitter: @sixrevisions.

The post The Single Var Pattern in JavaScript appeared first on Six Revisions.

No comments:

Post a Comment