How to make JSLint tolerate a leading semi-colon? - javascript

The continuous integration software I am using runs JavaScript files through JSLint and complains if they fail (using default JSLint settings it appears).
I've always prepended a ; to the start of my jQuery plugins, so concatenating them doesn't lead to something like this...
common.js
I don't have access to this file, and can't enforce a semi colon at the end.
var abc = function() {
alert(arguments[0]);
}
plugin.js
This is my file that is concatenated with common.js. It is appended straight to the end of common.js.
(function($) {
$.fn.somePlugin = function() {}
})(jQuery);
jsFiddle of the problem this can cause.
jsFiddle of the solution (leading semi-colon of my plugin).
However, JSLint complains with...
Error:
Problem at line 1 character 1: Unexpected space between
'(begin)' and ';'.
;(function($) {
Problem at line 1 character 1: Expected ';' at column 5, not column 1.
;(function($) {
Problem at line 1 character 2: Missing space between ';' and '('.
...
I tried using a bang operator (!) instead, and a few other alternatives, but JSLint still complained.
What can I do to get this safety net and pass JSLint?

Patch JSLint to not mind. Everyone will benefit.

Possibly a flippant answer, but your html can probably do this:
<script src="common.js"></script>
<script>;</script>
<script src="plugin.js"></script>
Or if you don't like the inline script on the second line, make a file called semicolon.js and, well, you know....
Sorry if this is ridiculous, but JSLint does not like a plain old empty statement on a line by itself. Somewhat unfortunate. Oh well.
BTW awesome fiddle. Seeing that alert run because of the missing semicolon after the var declaration of the function was, like, wow what do you know? That function got called as it should! Very interesting.

What happens if you put the ; on a line by itself, or put some other syntactically valid but meaningless statement like this:
"begin plugin";
(function() { // etc
EDIT: what about using void:
void("begin plugin");
(function() { // etc
//or
void(
(function() { /* your code */ })()
);
EDIT 2: what about some variation on this:
if (console && console.log) { // or if (false)?
console.log("Begining plugin definition");
}
(function { // etc

Related

correct js in tag manager

i am trying to add a tag (to custom javascript) to my google tag manager, but i get "Error at line 12, character 5: Parse error. primary expression expected". Can i please get help to correct my code?
<script>
var x=document.getElementById("ad"),
z=window.getComputedStyle(x,null),
y=z.getPropertyValue("display");
function showAdblockAlert()
{alert("You're missing ads, therefore turn off your AD-blocker!")
}function adBlockNotDetected()
{alert("Thank you for not using AD-blocker");
console.log
("no ad-blocker")}console.log(y);
"none",
==y?showAdblockAlert():adBlockNotDetected();
</script>
This code is odd. It combines some basic mistakes as well as advanced techniques if you can call that a ternary or using commas with a var.
Anyhow, your error is likely due to poor copying. The "none",== part, I think, got there from somewhere else.
Here, try this:
var x = document.getElementById("ad"),
z = window.getComputedStyle(x, null),
y = z.getPropertyValue("display");
function showAdblockAlert() {
alert("You're missing ads, therefore turn off your AD-blocker!")
} function adBlockNotDetected() {
alert("Thank you for not using AD-blocker");
console.log("no ad-blocker")
}
console.log(y);
y ? showAdblockAlert() : adBlockNotDetected();
You should know, however, that alerts in production is a very good way to get your site blacklisted one way or another.
Besides, declaring globals like that is a very bad idea.
Your code is unsafe. It relies on getComputedStyle to be there, as well as other elements. It throws errors otherwise.
Finally, the use of functions there seems to be a little excessive. They're not needed if you swap the ternary with a normal if, making the code much more readable.

Changing indentation style in atom editor (javascript code)

I've used microsoft's vscode for some months, but since 2 updates the indentation is broken for me, without a way to fix it. I therefore consider switching to atom. I was working with atom before, and never had this problem, but now it seems to have the same (wrong for me) behaviour as vscode:
if (xxx) // press enter here and type 'something();'
should result in
if (xxx)
something();
but it results in
if (xxx)
something();
It will work completely finde if you add { }, but without them its like the above.
How can I fix this in atom? The basic identation settings don't seem to cover this.
My way of doing this si to always use {} (also because I'm using linter-standard-js) That way, you type
if (myCondition) {}
When you return between the accolades, you get the following
if (myCondition) {
// indented and here you go
}
You can add extra conditions for Atom to change the indent level in your config.cson file, following the lead of the packages that define those conditions in the first place. Add the following to the top level of config.cson and Atom will automatically add a level of indentation after a line that matches the regular expression if\s*\(.*\)$. If you already have a .source.js entry, make sure to change that instead of just pasting this bit in.
'.source.js':
editor:
increaseIndentPattern: '(?x)
\\{ [^}"\']* $
| \\[ [^\\]"\']* $
| \\( [^)"\']* $
| if\\s*\\(.*\\)$
'

Javascript commenting practice

Recently, using comments in javascript I've run into a few questions about the commenting system. I wanted to comment on the name of a variable, so I put it right after declaring the name, on the same line, like this:
var wk /* (website key) */ = 1;
Now I think this is perfectly valid and works fine, right?
So a little while later, I wanted to comment out the whole block of code that line was on, like this:
/*
~ more code ~
var wk /* (website key) */ = 1;
~ more code ~
*/
But this doesn't work, because when the interior comment closes, it closes the whole comment. That seems kind of dumb to me. Is there any way to do nested comments in javascript?
You can't nest block comments, but you can do this:
var wk = 1; // website key
Or
// website key
var wk = 1;
It looks less awkward, and block comments are only really supposed to be used for... well, blocks. It's just better coding style in general.
Or, even better, make your code self-documenting and eliminate the need for a comment at all:
var websiteKey = 1;
I ran into a problem recently where I had written some JavaScript for a friend on their wordpress blog. Anyway long story short they used the WYSIWYG editor, witch reformatted the page source.
so
<script type="test/javascript">
$(function() {
// this is a button click handler
$('#button').click(function () {
// did some stuff
});
})();
</script>
turned into
<script type="test/javascript">
$(function() {// this is a button click handler $('#button').click(function() {
// did some stuff }); })(); </script>
The point of the story is always be aware of your environment and the needs of your users, even when commenting
Do it like this:
var wk = 1; //Website Key - Additional Info Here
then if you need to comment the block, you can do
/*
Comments and stuff go here...
var wk = 1; //Website Key - Additional Info Here
*/
Avoid nested block comments. They are forbidden in the ECMA Script specification. If any interpreters allow this now, they may not in the future.
From Section 7.4,
Comments can be either single or multi-line. Multi-line comments cannot nest.
You never put single-line comment between the code. Reasons are that it is not readable enough and not being followed in the community as a best practice.
Putting away code via commenting it out is easily done with multi-line comment tags /* ... */ or single line ones //.
PS: For commenting I suggest to avoid doing magic stuff. I would not encourage nested commented at all! For having a consistent commenting style in Javascript try follow a pattern like JSDoc. In JSdoc, while commenting a block of code, you can do something like this:
/***
*
* #param param1
*/
var aFunction = function(param1) {
};
Readable, clean and no magic tric. It is great since it also embeds some sort of static type checking (I know JS is dynamically typed). Also check out this video from one of the guys behind integrating JSDoc into Intellij & Webstorm: Dmitry Jemerov: Static types in JavaScript: what, how and why

Google closure compiler javascript parse error

I am trying to use google closure compiler on my javascript files. It works fine except for the following piece of code:
function goto(form) { var index=form.select.selectedIndex
if (form.select.options[index].value != "0") {
location=form.select.options[index].value;}}
The compiler returns:
JSC_PARSE_ERROR: Parse error. missing ( before function parameters. at line 1 character 9
function goto(form) { var index=form.select.selectedIndex
There is a caret (^) pointing to the g in "goto" when it is output on the screen.
I am using just the basic UI version here to test:
http://closure-compiler.appspot.com/home
Any idea what is wrong with the javacript? It seems to work just fine but I am not a javascript person so I have no clue how to fix it. Thanks,
Bill
I am not sure why #Sirko deleted his answer. So I will add it.
You need to change the name of the function goto to something else. Something like gotoUrl, gotoPage, etc.
It was a reserved word in ECMAScript 3, but removed in ECMAScript 5. I am guessing the closure compiler uses that older list still.

JavaScript REGEX extend `/pattern/` with custom functions

I know I can do this...
RegExp.prototype.xtend = function(){ console.log(123) }
y = new RegExp(/pattern/)
y.xtend()
I want to extend regex patterns in this format: /pattern/, so I can do...
/pattern/.xtend()
Edit: It was a problem with syntax
Turns out it was a missing semi-colon. I need a semi-colon before the regex pattern otherwise it gives syntax error.
Thanks for all the comments. Works great now.
Turns out it was a missing semi-colon. I need a semi-colon before the regex pattern otherwise it gives syntax error.
I was running this in Firebug console, which automatically returns the value of the last line... but because there is no semi-colon after the third line, and the fourth starts with a regex, it was getting an error.
RegExp.prototype.xtend = function(){ console.log(123) }
y = new RegExp(/pattern/)
y.xtend()
/pattern/.xtend()
Adding the semi-colon solves the problem...
RegExp.prototype.xtend = function(){ console.log(123) }
y = new RegExp(/pattern/)
y.xtend(); // <~~ this semi-colon fixes the issue
/pattern/.xtend()
Thanks for all the comments. Works great now.

Categories