Indent Style in JavaScript
Few weeks ago, I have seen a video clip titled with ‘JavaScript: The Good Parts‘ on YouTube, presented by Douglas Crockford, where he did mention the way of writing JS code. I was agreed with what he said, the way to govern indentation of blocks of code shouldn’t be subjective. Different developers or programmers have their own preferred of code indentation when writing program. However, in JavaScript, you are highly encouraged to use BSD KNF style, which is also known as ‘Kernel Normal Form’. Why do I say so? I will show you what thing goes wrong later.
I understand that, those programmers who come from C/C++ or C# background, commonly write their code in K&R style, which is typically place the first curly brace at the following line just after the declaration, and ended by another curly brace. However, there is a pitfall when writing this style in JavaScript. Well, without talking much, why not we just take a look at the code, as follows:
Code A:
//ERROR: Silent and returned 'undefined' value function myFunction() { //some code here... return; { name1: value1, name2: value2 } }
Code B:
//valid, returned object literal notaton function myFunction(){ //some code here... return { name1: value1, name2: value2 } }
At the first glance, both of the examples look identical and return the same result. Whereas, the declared function will return an object literal notation, in name-value pairs. But, if you look closely, it’s actually returning two different results. In Code A example, we exit the function immediately when ‘return’ is encountered, and therefore return ‘nothing’, because of the object literal {} are located at the next line of ‘return’ reserved word. In other words, the following code will not be executed and ‘undefined’ value is returned. (I added a semicolon (;) after ‘return’ word to make code looks clearer, which should indicate the end of the current line of code.)
Conversely, if you look at the Code B, which is written in BSD KNF style, the code is perfectly executed and an object literal notation is returned. This is because of the first curly brace of the object literal is recognized when we put it just after the ‘return’ reserved word. Apparently, it returns a value here; the said object literal.
Good Practice
So, what is the key point from the above example? The conclusion is, just try make it as a good practice to indent the code by using BSD KNF style, especially in JS. It’s surely alright if you are using other indentation patterns. Of course, it’s still valid. But, somehow, in certain circumstances, you might be creating problems or pitfalls without your conscious and getting the unexpected results, just like the case I mentioned previously.
NOTE:
This post is not comparing the pros/cons between ‘BSD KNF style’ and ‘K&R style’. The writer just borrowed the terms to make thing clearer and for better explanation.No related posts.
