Why no semicolon at the end of js expression in javascriptmvc app? - javascript

I am starting to learn javascriptmvc, and in code samples, I see code without semicolons at the end of expressions. Does this count on automatic semicolon insertion or am I missing something? Code example below:
$.Controller("Contacts.Controller", {
init: function(){
this.params = new Mxui.Data();
$("#category .list_wrapper").mxui_data_list({
model : Contacts.Models.Category,
show : "//contacts/views/categoryList",
create: "//contacts/views/categoryCreate"
}) // <------ NO SEMICOLON
$("#location .list_wrapper").mxui_data_list({
model : Contacts.Models.Location,
show : "//contacts/views/categoryList",
create: "//contacts/views/categoryCreate"
}) // <------ NO SEMICOLON
$("#company .list_wrapper").mxui_data_list({
model : Contacts.Models.Company,
show : "//contacts/views/companyList",
create: "//contacts/views/companyCreate"
}) // <------ NO SEMICOLON
// etc...
}
}) // <------ NO SEMICOLON

Javascript can be forgiving about the lack of a semicolon in ways that other languages are not. However a semicolon is recommended where you've pointed them out.
If you run the code you've given through JSLint, it throws up a whole stack of warnings, including complaining about those missing semicolons.
JSLint is a tool for telling you about things in your code which may not be syntax errors but which could cause problems. It generally throws up a lot of errors, even for relatively well written code, but it is good for picking up things which you should fix.
I would say that those code samples are poorly written because of the missing semi-colons.

Semicolons are only mandatory in inline event handlers.
MOST anywhere else, a linefeed is enough. Here is an example of where it is not enough:
Why is a semicolon required at end of line?
And as pointed out, do not leave out semicolons if you want to minify your scripts.

A lot of semicolons are optional in javascript, though recommended to avoid confusion
https://mislav.net/2010/05/semicolons/

Related

Is always putting a semicolon after an end curly-brace a bad idea?

I sometimes like to work quickly, so I set a macro in my editor to always add a semicolon after an end curly-brace, even when not necessarily needed. For example:
var test=function(){
//I realize the semicolon after the curly-brace below is required
};
function test(){
//But is it safe to have on where it isn't required, like below?
};
As in, will it create errors, slow down the site, or create compatibility issues? I will remove these additional semicolons when I am finished developing the product, but for now, is it OK?
Note that there are cases where adding a semicolon after an ending curly bracket can cause issues, e.g.:
let data = {
item1: [],
item2: {}; // This semicolon is a syntax error
};
On a program level, it makes no difference to have this:
function() {
};
Or this:
function() {
}
I do recommend that you pick one way to do it and stick with it for the purpose of consistency.
You should also read through this post:
Do you recommend using semicolons after every statement in JavaScript?
A lot of good points on this subject are made there.

Basic JS Q after "validation" with JSLint

I just ran one script through JSlint and received tons of errors - all related to the example below. Now I need to clear some basics, as I'm honestly pretty new to JS and don't know if those are "critical" Errors, Warnings or notices.
var whatEver = {
foo: null,
fooArray: [],
// This tells me that the curly bracket was expected much earlier
barArray:
{
whatever: 'somestring'
,keyTwo: 'anotherstring'
},
// Here I get told that I got "wrong" white spaces
bar: document.getElementById( 'someID' )
};
I know most of this is "basic" js stuff and so far everything's working fine. I just want to know if I'm making basic mistakes.
Thanks.
Here is some feedback:
It's not that normal to have a lot of whitespace after property names. Maybe it's a copy/paste problem.
Objects as shown by the {} are not arrays, FYI. SO you might not wants to call them arrays. You can make an array literal by using [], if that's what you want.
document.getElementById( 'someID' ); should NOT have a semi-colon at the end. That's your biggest mistake.
You sometimes use comma-before syntax and sometimes use comma-after. You could probably just stick with one. Personally, most of my JS is in node and comma-before is pretty normal there. Either works though. http://css-tricks.com/7741-commas-before/
I put this in my code example, but didn't mention it up here. Braces should always be on the line with the parent. This is because of automatic semi-colon insertion, which can screw you up if you put a return on the line before {}. See: http://robertnyman.com/2008/10/16/beware-of-javascript-semicolon-insertion/. Thanks Michael for mentioning it below!
Here's what I'd go with. http://jsfiddle.net/n87Cn/ JSLINT doens't like it, but I think it's quite nice.

JSLint, else and Expected exactly one space between '}' and 'else' error

Why JSLint report in code:
function cos(a) {
var b = 0;
if (a) {
b = 1;
}
else {
b = 2;
}
return b;
}
error:
Problem at line 6 character 5: Expected exactly one space between '}' and 'else'.
This error can be turned off by disabling Tolerate messy white space option of JSLint.
Or in other words -- why syntax:
} else { is better then
...
}
else {
...
Google also uses syntax with } else { form.
But I don't understand why. Google mentioned ''implicit semicolon insertion'', but in context of opening {, not closing one.
Can Javascript insert semicolon after closing } of if block even if next token is else instruction?
Sorry that my question is a bit chaotic -- I tried to think loud.
JSLint is based on Crockford's preferences (which I share in this case).
It's a matter of opinion which is "better".
(Although clearly his opinion is right ;)
It's not a matter of style. It's how ECMAScript works.
For better or for worse, it will automatically insert semicolons at the end of statements where it feels necessary.
JavaScript would interpret this:
function someFunc {
return
{
something: 'My Value'
};
}
As this:
function someFunc {
return;
{
something: 'My Value'
};
}
Which is certainly what you don't want.
If you always put the bracket on the same line as the if and if else statement, you won't run into a problem like this.
As with any coding language, the coding style chosen should be the one that minimizes potential risk the most.
Mozilla Developer Network also promotes same line bracketing: https://developer.mozilla.org/en-US/docs/User:GavinSharp_JS_Style_Guidelines#Brackets
JSLint is being very picky here, just enforcing a style that you might not share.
Try JSHint instead:
The project originally started as an effort to make a more configurable version of JSLint—the one that doesn't enforce one particular coding style on its users [...]
JSLint is just being picky here. The guy who wrote it also baked in many stylistic suggestions in order to keep his own code more consistent.
As for semicolon insertion, you shouldn't need to worry here. Inserting a semicolon before the else clause would lead to a syntax error and automatic semicolon insertion only occurs in situations where the resulting code would still be syntactically valid.
If you want to read more on semicolon insertion, I recommend this nice reference
Basically if you insert semicolons everywhere you only need be careful about putting the argument to "return" or "throw" (or the label for "break" and "continue") on the same line.
And when you accidentally forget a semicolon, the only common cases that are likely to bite you are if you start the next line with an array literal (it might parsed as the subscript operator) or a parenthsised expression (it might be parsed as a function call)
Conclusion
Should you omit optional semicolons or not? The answer is a matter of
personal preference, but should be made on the basis of informed
choice rather than nebulous fears of unknown syntactical traps or
nonexistent browser bugs. If you remember the rules given here, you
are equipped to make your own choices, and to read any JavaScript
easily.
If you choose to omit semicolons where possible, my advice is to
insert them immediately before the opening parenthesis or square
bracket in any statement that begins with one of those tokens, or any
which begins with one of the arithmetic operator tokens "/", "+", or
"-" if you should happen to write such a statement.
Whether you omit semicolons or not, you must remember the restricted
productions (return, break, continue, throw, and the postfix increment
and decrement operators), and you should feel free to use linebreaks
everywhere else to improve the readability of your code.
By the way, I personally think that the } else { version is prettier. Stop insisting in your evil ways and joins us on the light side of the force :P
I have just finished reading a book titled Mastering JavaScript High Performance. I speak under correction here, but from what I can gather is that "white space" does in fact matter.
It has to do with the way the interpreter fetches the next function. By keeping white space to a minimum (i.e.) using a minifier when your code is ready for deployment, you actually speed up the process.
If the interpreter has to search through the white space to find the next statement this takes time. Perhaps you want to test this with a piece of code that runs a loop say 10,000 times with white space in it and then the same code minified.
The statement to put before the start of the loop would be console.time and finally console.timeEnd at the end of the loop. This will then tell you how many milliseconds the loop took to compute.
The JSLint error/warning is suggesting to alter code to
// naming convention winner? it's subjective
} else if{
b = 2;
}
from:
}
else if{
b = 2;
}
It prevents insert semicolons; considered more standard & conventional.
most people could agree a tab between the
}tabelse if{
is not the most popular method. Interesting how the opening bracket { is placed (space or not) obviously both ar subjected

Unexpected "unexpected end of line" JavaScript lint warning

This is my JavaScript (much stripped down):
function addContent() {
var content = [];
content.append(
makeVal({
value : 1
})
); // Generates lint message
}
Running a lint program over this, I get the message
unexpected end of line; it is ambiguous whether these lines are part of the same statement
on line 7. If I concatenate lines 6 and 7 the message goes away.
Can anyone explain where this ambiguity is? It seems to me that the parenthesis on line 7 is unambiguously closing the call to append().
It looks that way to me, too. Sounds like a bug in the lint program you're using.
You can understand why it would wonder, because the call to makeVal fits the profile of code that's relying on semicolon insertion — unless you look correctly at the wider context and realize it's within argument list for the append call. Seems to me the lint program is not actually parsing the language, just looking for patterns, which is going to mean it's going to have both false positives and false negatives.

Javascript packing problem

I have a minified/packed javascript file which is causing problems. The issue is that the non-packed input file has some missing semicolons somewhere which aren't a problem when there's line breaks, but when the file is packed, the line breaks are removed and that causes a parser error. For example:
//input
var x = function() {
doSomething();
} // note: no semicolon
var y = 'y';
//----
// output
var x=function(){doSomething();}var y='y';
// error here: ^
The strange thing is that when I do a replace on the output file to replace all semicolons with a semicolon and a new line, the file works! This is making it ludicrously hard to find the error, since AFAIK, I can't think of any situation where a line break after a semicolon should change anything. Any ideas about why doing this replace would make it work?
Uh... Have you tried JSLint?
When there's a line break, there's an implied semi-colon.
Use jslint to check your code. If you do this and get it passing with regards to semicolons, it should pack correctly.
In JavaScript, semicolons are implicitly added at newlines. This introduces situations that can be ambiguous. This blog post: http://robertnyman.com/2008/10/16/beware-of-javascript-semicolon-insertion/ describes the problem succinctly and gives an example.
JSlint is a good solution. Also, some code editors will find these kinds of errors for you. If I recall correctly, NetBeans catches these in realtime, as you type. I believe Komodo and Aptana do as well.

Categories

Resources