I just watched a video of Douglas Crockford's presentation about his 2009 book JavaScript: The Good Parts.
In the video, he explains that the following block is dangerous because it produces silent errors:
return
{
ok: false
};
And that it should actually be written like this (emphasising that although seemingly identical the behavioural difference is crucial):
return {
ok: false
};
You can see his comments around 32 minutes into the video here: http://www.youtube.com/watch?v=hQVTIJBZook&feature=player_embedded#!&start=1920
I have not heard this before, and was wondering if this rule still applies or if this requirement in syntax has been overcome by JavaScript developments since this statement was made.
I found this very interesting as I have NOT been writing my code this way, and wanted to check that this information was not out of date.
Block Format Formatting rule for the block style is that the letter is left-justified. For example, the address and date is on the left; drop down two lines for the salutation. Drop down two lines and begin the body on the left-hand side of the paper. Start the body at the left side and do not indent.
Letters written in block style have every line aligned at the left margin. This makes them easy to read and quickly. The standard block letter style and its variations are meant to be used as guides to help you format letters.
Block format is typically used for business letters. In block format, the entire text is left aligned and single spaced. The exception to the single spacing is a double space between paragraphs (instead of indents for paragraphs).
Why is using a modified block style letter important? Like all letters, concise, well-written content is important for getting your message across to your reader. Using a familiar letter format such as modified block style shows the recipient your professionalism.
The silent error is that undefined
is returned!
Semicolons are optional in JavaScript, and therefore
return
{
ok: false
};
is parsed as if it were
return; // Leaves function straight away
{
ok: false
};
JSLint will recognize such patterns and warn about them:
lint warning: unexpected end of line; it is ambiguous whether these lines are part of the same statement
lint warning: missing semicolon
lint warning: unreachable code
lint warning: meaningless block; curly braces have no impact
This has been discussed on SO in the "Strangest language feature" question.
The rule still applies.
Because the language automatically inserts "missing" semi-colons, the first snippet is interpreted as:
return;
{
ok: false
};
I.e, undefined
is returned. If the code was somehow permitted to run past the return
statement, an object would then be created, but would not be assigned to anything useful (a variable).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With