Skip to content

Latest commit

 

History

History
42 lines (31 loc) · 1.17 KB

javascript-style-why-its-important.md

File metadata and controls

42 lines (31 loc) · 1.17 KB
title date published tags modified
JavaScript Style - why it's important
2007-11-21 13:33:16
true
media
code
javascript
2014-09-03 16:15:12

JavaScript Style - why it's important

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.