Re:Javascript patterns
by russellsprouts on Thursday January 02, 2014 @01:30AM
(#6998494)
Rather than putting a semi-colon after every function declaration, I would suggest the Lua convention -- put the semi-colon at the beginning of the line that could cause issues. An empty statement is valid is JavaScript, so this should work in all cases I can think of:
;(function(){
var foo = 1;
console.log(foo);
})()
In Lua, whitespace is very nearly all the same. For example: a = 1 b = 2
c
=
3
is valid Lua code. However, lines that start with parens have the same ambiguity: a = something
(expression)(arguments)
--Could be:
a = something(expression)(arguments);
--Also could be:
a = something;
(expression)(arguments);
The parser will complain about the ambiguity. If the intention is to have 1 statement, they should probably be on the same line, otherwise the convention is to put the semi-colon at the beginning of the second line: a = something
;(expression)(arguments)That would be a change of paradigm because no JavaScript standard -or library- does that. Plus it feels wrong because the spoken language equivalent would be something like:
The quick brown fox jumps over the lazy dog
. The fox didn't say anything that day
, because in all honesty what does the fox say
?I think I've been unclear. When I say function definition I'm referring to this:
function foo() {
console.log('bar');
}
And when referring to a function expression I'm talking about this: var foo = function () {
console.log('bar');
};
The latter needs to be terminated with a semicolon to prevent ambiguity (in some situations), while the former does not. This for example is valid JavaScript: function foo() {
console.log('bar');
}foo=5
And function declarations can create ambiguous code, because functions are first class citizens on JavaScript it means code like this is valid:
but for the lacking semicolon it throws an error if it is followed by: