I adopted Douglas Crockford's JavaScript code convention some time ago, but at yesterday's @media Ajax he demonstrated, in a beautifully simple way, why it's really important.
The following two examples look the same, but they're not:
// the right way
return {
'ok': false
};
// the wrong way
return
{
'ok': false
};
The reason why the second way is wrong, is because JavaScript's semicolon injection in the second version is actually processed as this:
return; // which returns undefined
// block level of code that does nothing
{
'ok': false
}
; // this last semicolon is executed as a dummy line
The return
code doesn't fail or throw any errors, but as soon as you try to access your result, your code will break since the returned value is undefined
rather than an object
.