JavaScript the hoisting effect

JavaScript is one of the most talked about programming languages of the day. Being the language of the browser any modern programmer, developer or web designer cannot avoid it. It’s even sneaking onto our servers with courtesy of the node.js project. If you’re new to JavaScript there are a few ‘features’ that may trip you up, especially if you have been using a class based language. Take the following example in Java:

	public static void main(String[] args) {
		
		List<String> list = null;
		
		if((list = coloursInImage(img1)) != null) {
			
			int iNoOfColours = 0;
			
			iNoOfColours += list.size();
			System.out.println(iNoOfColours);
			
		}
		
		if((list = coloursInImage(img2)) != null) {
			
			int iNoOfColours = 0;
			
			iNoOfColours += list.size();
			System.out.println(iNoOfColours);
		}
	}

In Java the variable iNoOfColours will hold the size of the list as returned by the method ‘coloursInImage’. So if img1 has 8 colours and img2 two has 256 colours we’d see those numbers printed to the output window.

Let’s look at the JavaScript equivalent:

	var list = null,
		img1, img2;

	if((list = coloursInImage(img1)) !== null) {

		var iNoOfColours = Number();
		
		iNoOfColours += list.length;
		console.log(iNoOfColours);

	}

	if((list = coloursInImage(img2)) !== null) {

		var iNoOfColours;
		
		iNoOfColours +=	list.length;
		console.log(iNoOfColours);
	}

In JavaScript the variable iNoOfColours will hold the size of the array as returned by the method ‘coloursInImage’. So if img1 has 8 colours and img2 two has 256 colours we’d expect to see those numbers printed to the output window. However, we actually get 8 and 264. This is because of the hoisting effect – specifically how JavaScript works when handling declaration statements (var). Regardless of where a variable is declared, its declaration is hoisted to the top. The key here is to understand the declaration and initialization steps are treated separately and only the declaration will be hoisted. In our example, the first declaration also initialises the variable to 0. We then simply increment the variable’s value (zero) by the length of the array; thus, when repeating this within the second if-statement we end up summing the two. This is because the second declaration of the variable has been hoisted. The effect of which is that the expected scope does not mirror that we’d expect in Java. Something to watch out for!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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