Basic JS Q after "validation" with JSLint - javascript

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.

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.

Simple way to check/validate javascript syntax

I have some big set of different javascript-snippets (several thousands), and some of them have some stupid errors in syntax (like unmatching braces/quotes, HTML inside javascript, typos in variable names).
I need a simple way to check JS syntax. I've tried JSLint but it send too many warnings about style, way of variable definitions, etc. (even if i turn off all flags). I don't need to find out style problems, or improve javascript quality, i just need to find obvious syntax errors. Of course i can simply check it in browser/browser console, but i need to do it automatically as the number of that snippets is big.
Add:
JSLint/JSHint reports a lot of problems in the lines that are not 'beauty' but working (i.e. have some potential problems), and can't see the real problems, where the normal compiler will simply report syntax error and stop execution. For example, try to JSLint that code, which has syntax errors on line 4 (unmatched quotes), line 6 (comma required), and line 9 (unexpected <script>).
document.write('something');
a = 0;
if (window.location == 'http://google.com') a = 1;
document.write("aaa='andh"+a+"eded"');
a = {
something: ['a']
something2: ['a']
};
<script>
a = 1;
You could try JSHint, which is less verbose.
Just in case anyone is still looking you could try Esprima,
It only checks syntax, nothing else.
I've found that SpiderMonkey has ability to compile script without executing it, and if compilation failed - it prints error.
So i just created small wrapper for SpiderMonkey
sub checkjs {
my $js = shift;
my ( $js_fh, $js_tmpfile ) = File::Temp::tempfile( 'XXXXXXXXXXXX', EXLOCK => 0, UNLINK => 1, TMPDIR => 1 );
$| = 1;
print $js_fh $js;
close $js_fh;
return qx(js -C -f $js_tmpfile 2>&1);
}
And javascriptlint.com also deals very good in my case. (Thanks to #rajeshkakawat).
Lots of options if you have an exhaustive list of the JSLint errors you do want to capture.
JSLint's code is actually quite good and fairly easy to understand (I'm assuming you already know JavaScript fairly well from your question). You could hack it to only check what you want and to continue no matter how many errors it finds.
You could also write something quickly in Node.js to use JSLint as-is to check every file/snippet quickly and output only those errors you care about.
Just use node --check filename
Semantic Designs' (my company) JavaScript formatter read JS files and formats them. You don't want the formatting part.
To read the files it will format, it uses a full JavaScript parser, which does a complete syntax check (even inside regular expressions). If you run it and simply ignore the formatted result, you get a syntax checker.
You can give it big list of files and it will format all of them. You could use this to batch-check your large set. (If there are any syntax errors, it returns a nonzero error status to a shell).

Please explain this usage of a colon in javascript

I'm making a library, and I often inspect the result of Closure Compiler's output to see how it's doing things (I do have unit tests, but I still like to see the compiled code for hints of how it could compress better).
So, I found this very weird piece of code, which I never seen before.
variable : {
some();
code()
}
Note: this is not an object literal! Also, there is no ? anywhere that would make it a ?: conditional.
That code is in a regular function block (an IIFE).
variable, in this case, is an undefined variable. There's no code making it true, false, or whatever, and just to make sure, I put a console.log in there and indeed, I get a ReferenceError.
Please do note that I test my code in IE8 too, so this isn't just in modern browsers. It seems to be standard, plain old javascript.
So let's experiment with it. Firing up Chrome's console, I get this:
undeclaredVariable:{console.log('does this get logged?')} // yes it does.
trueValue:{console.log('what about this?')} // same thing.
falseValue:{console.log('and this?')} // same thing.
but then...
(true):{console.log('does this work too?')} // SyntaxError: Unexpected token :
...and...
so?{console.log('is this a conditional?')}:{alert(123)} // Unexpected token .
So what does it do?
thisThing:{console.log('is used to declare a variable?')}
thisThing // ReferenceError: thisThing is not defined
Please, I'd love it if someone could explain to me what this code is meant to do, or at least what it does.
It is a label
Provides a statement with an identifier that you can refer to using a
break or continue statement.
For example, you can use a label to identify a loop, and then use the
break or continue statements to indicate whether a program should
interrupt the loop or continue its execution.
Another common place you see it is when people stick the wonderful and useless javascript: on event handlers.
This is a label (the bit ending with a colon) followed by a block (the code surrounded by the curly brackets).
Blocks usually follow control statements, like if(...) { /*block*/ }, but they can also simply stand on their own, as in your example.
Labels allow jumping up several loops at a time with a continue or break; see the linked MDN page for several examples, such as:
var itemsPassed = 0;
var i, j;
top:
for (i = 0; i < items.length; i++){
for (j = 0; j < tests.length; j++)
if (!tests[j].pass(items[i]))
continue top;
itemsPassed++;
}
Here, top: is a label that code inside the inner loop can jump to, in order to escape to the outer loop.
For the sake of anyone who doesn't know what JSON is, and sees a colon in what might actually be an object, and is trying to figure out what it is, and finds this discussion, a colon is also used in JSON. There is a practice of embedding functions in a JSON object. Which might be confusing (As it was to me) for anyone who happens to see this for the first time. (Everyone isn't born with the knowledge of JSON and JavaScript programmed into their brains.) So if you find yourself at this discussion, and you think that every time you see a colon in JavaScript, that it's a label, it might not be. It might be that it's a colon after a label, OR it might be part of JSON. In fact, a colon in JSON being shown as a string, is a lot more common than a label. JSON in the form of an object, will be displayed as [object Object], with all the content hidden. So, unless the JSON is in the form of a string, and you display an object to the console (console.log(object)) all you will see is [object Object]. It is common practice to write JavaScript code, wrapped in an object. In that case you will see the JSON in the form of code. That's when you'll ask yourself, "What is this? and what is that colon for?" Then you'll find yourself at this discussion, and be told that it's a label, when it's really part of JSON. The topic of this discussion is worded: "Please explain this usage of a colon in javascript", and then the "correct answer" is marked as having to do with a label. The correct answer is that a colon can be used in more than one way. So, if you don't know what JSON is, or think you know (like I did, but didn't really understand) read about it here:
JSON.org
That is just a label.
you can use continue [label name] (or break) in a loop to go to a label.
More explanations of what they are can be seen throughout the interwebs.
it is used for labeling an statement in jsvascript.check more detail here.
the labeled statement can be used with break and continue later.

Razor/JavaScript and trailing semicolon

Using Visual Studio 2012, on a Razor view page, in the JavaScript section, I am getting what I think is a battle between Razor syntax vs JavaScript syntax. In particular, the trailing semicolon in the script section is flagged by intellisense and a compiler warning (not error) is delivered:
'Warning 13 Syntax error'.
If I remove it, then I get a statement termination recommendation (ReSharper in this case, but just good practice).
<script type="text/javascript">
$().ready(function(){
var customer = #Html.Raw(ViewBag.CustomerJSON); // <- Razor (I think) doesn't like this semicolon
});
</script>
Is this a bug in Razor? If so, is there a way I can rewrite this to avoid this issue?
Is this a bug in Razor?
Absolutely not. Run your application, and it will work as expected.
It is a bug in the tools you are using (Visual Studio 2012, ReSharper, ...) that are incapable of recognizing perfectly valid syntax and warning you about something that you shouldn't be warned about. You could try opening an issue on the Microsoft Connect site and signalling this bug if that hasn't already been done.
Since this still seems to be happening and it is a nuisance I figured I will at least let others know what I ended up using as a "hack". I don't want to ignore the warning and would rather accept a hokier syntax (and yes someone is going to say this will kill performance :))
What I use as a workaround is to use a client side addition at the end. For me this error occurred on defining an "integer" constant, so
window.foo = #(Model.Something);
gave me the good old semicolon error. I simply changed this to:
window.foo = #Model.Something + 0;
(In the stated questions case you should just be able to add '', so + ''.
I know there is a whole another addition happening on the client and it isn't elegant, but it does avoid the error. So use it or don't, but I prefer this over seeing the warning/error.
If someone knows of a server-side syntactical workaround for this I would prefer this to the client-side one, so please add.
I found that wrapping the Razor syntax in a JavaScript identity function also makes the IDE happy.
<script type="text/javascript">
#* I stands for Identity *#
function I(obj) { return obj; }
$().ready(function(){
var customer = I(#Html.Raw(ViewBag.CustomerJSON));
});
</script>
This worked for me:
var customer = #Html.Raw(ViewBag.CustomerJSON + ";")
Here's a workaround for booleans:
var myBool = #(Model.MyBool ? "true;" : "false;")
This worked for me
#Html.Raw(string.Format("var customer = {0};", ViewBag.CustomerJSON));
<script type="text/javascript">
$().ready(function(){
var customerName = ('#ViewBag.CustomerName'); // <- wrap in parens
});
</script>
Isn't it as simple as wrapping in parentheses? Putting values through the console seem to work fine with no side effect.
It works for strings, but it still gives the error for non-quoted values, but I still like this for string values. For numbers you could just use parseInt('#Model.TotalResultCount', 10).

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

Categories

Resources