JavaScript declarations best practice

JavaScript converts all variable declarations into a single var, separating variables by commas.  It is good practice to do the same as we code, in order to speed up process, and most importantly, to avoid being misinterpreted.

// Single variable declaration:
var x = 10;
// multiple variables declaration:
var y = 5,
	z = 7,
	a = "Hi there"
;
// above, notice the semicolon at the end (and no comma after the last item)
// And in loops:
var i;
for (i = 0; i < 5; i++)
// be aware that unless a loop is inside of a function, 
//i will remain global after the loop is over, holding the very last value.

It is best to declare all variables on the top of their scopes. In Function scope they can also be grouped with one single var.

// variable declaration inside of functions
function xyz(num){
var c = 10,
    d = 2
	;
return c * num / d;
};

JavaScript makes two passes to the code. The first pass is called hoisting.

When the interpreter scans the code it makes one first pass and gathers variable declarations and function names making a menu of what is available. At this point JavaScript does not yet know what is in each hoisted variable (pulled to top) and they all have the same value: undefined.

On the second pass that’s when JavaScript finally gathers the value of each variable making up an execution environment or execution context, good only for that moment in time. This execution context is never the same since JavaScript is like water in a river, it never looks back. It may push some variables forward but each execution context is unique.

You can read more about those issues on my latest book.

If you love JavaScript like I do, you will enjoy reading it.
Use the free amazon “Kindle for PC” app to read it on your computer.

Advertisements

Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s