The enduring popularity of this question on Stackoverflow: How to do this using jQuery – document.getElementById(“selectlist”).value took me back to the very first issue I had with jQuery. Namely:

Why on earth does $(“myid”) not give me the DOM object for “myid” like document.getElementById(“myid”)?

In fact it gives you a collection of all elements <myid> which for this is almost certain to be empty.

But no-one explains this to you. No-one takes you aside and says, “listen, forget the DOM, forget all its functions, pretend it never existed…this is all DIFFERENT”…or something.

This is the first thing you should know about jQuery. Everything else is trivial.

As I intimated in my answer $() and document.getElementbyId are “Equivalent”.

Being in the right place at the right time to answer this question was fortunate, and was the Stackoverflow equivalent of a Jackpot if you care about your reputation points. Here is the answer I gave, and how it looks after four revisions:

While…

$('#selectlist').val();

…is equivalent to…

document.getElementById("selectlist").value

…it’s worth noting that…

$('#selectlist')

…although ‘equivalent’ is not the same as…

document.getElementById("selectlist")

…as the former returns a jQuery object, not a DOM object.

To get the DOM object(s) from the jQuery one, use the following:

$('#selectlist').get(); //get all DOM objects in the jQuery collection
$('#selectlist').get(0); //get the DOM object in the jQuery collection at index 0
$('#selectlist')[0]; //get the DOM objects in the jQuery collection at index 0

It should also be noted that the return from $() is a collection, and may contain MANY items. If you are selecting by ID (using #) then you will only ever get one item

, , ,

Techmeetup Edinburgh have just updated their Vimeo page with the talk I gave on JavaScript linting and hinting earlier this month.

As a reminder. The slides and references from the talk are available here: Material From Techmeetup Talk

 

, , , ,

JavaScript Static Analysis Talk

Here is the material from my Techmeetup talk in Edinburgh on Wednesday 11th July

Many thanks to those that attended, hope you enjoyed it.

 

Slides

The Prezi presentation is available here: http://prezi.com/nlwom16jo6z7/javascript-static-analysis/

 

Demo App

Code location [TBD]

 

Eval is Evil

http://www.jameswiseman.com/blog/2011/03/31/jslint-messages-document-write-can-be-a-form-of-eval/

http://www.jameswiseman.com/blog/2011/01/18/jslint-messages-eval-is-evil/

 

JavaScript Popularity

http://www.quora.com/Is-JavaScript-the-most-popular-programming-language-in-the-world

http://langpop.com/

http://www.tiobe.com

 

Beautification/Minification – Competing Goals

“Assembly Language of the Web”

http://bit.ly/ntq0aI

http://bit.ly/n3rPIR

 

Date Initialsation

http://jsfiddle.net/es4XW/

http://hexmen.com/blog/

 

ParseInt – Strange Base 19 Conversion

http://stackoverflow.com/q/11340673/144491

 

Performant Numeric Conversion

http://stackoverflow.com/q/2665984/144491

 

JSLint

http://www.jslint.com/

 

Crockford Quotes

http://tech.groups.yahoo.com/group/jslint_com/message/1688

https://github.com/twitter/bootstrap/issues/3057#issuecomment-5135562

http://wonko.com/post/jsmin-isnt-welcome-on-google-code

 

JSHint

http://www.jshint.com/

http://anton.kovalyov.net/2011/02/20/why-i-forked-jslint-to-jshint/

http://brendaneich.com/2010/11/paren-free/

 

Browser Integration

WScript Files: http://jameswiseman.com/jslint/

Netbeans Plugin : http://plugins.netbeans.org/plugin/40893/jslint

Eclipse Plugin : http://stackoverflow.com/questions/2741058/jslint-eclipse-plugin

Eclipse Plugin additional info: http://stackoverflow.com/questions/2741058/jslint-eclipse-plugin

Emacs Plugin: https://github.com/daleharvey/jshint-mode

 

Google Closure Compiler

http://closure-compiler.appspot.com/home

https://developers.google.com/closure/compiler/docs/error-ref

 

Google Closure Linter

https://developers.google.com/closure/utilities/

http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

http://code.google.com/p/closure-linter/source/browse/#svn%2Ftrunk%2Fclosure_linter

 

, , , ,

I stumbled across this message recently during the course of developing a bespoke jQuery plugin for one of our systems.

The offending code in question was

/*****************************************************************************/
/*Private functions.
/*****************************************************************************/

Given its structure, I found myself blinded to the offending code until I spotted that I had indeed omitted the closing ‘*/’ from the second line.

The message it yielded in full was:

Stopping, unable to continue. (4% scanned).

This message is easy enough to understand, but it’s one of those that causes JSLint to halt in its tracks

The omission of a closing statement to any block of code can result in inadvertently nesting any proceeding code. Block comments are more forgiving of the omission, because the second opening ‘/* will be treated as a comment itself.

However, consider the following:

/*Private functions.    /*Nested Comment*/   */

In the above code, the first close-comment will close everything, and the second will be left dangling. This is even shown up by the syntax-highlighter (if you can see it).

One user did ask this question of Douglas Crockford, who responded

JSLint stops because it sees comments that are nested. That is usually
an indication of a serious coding error. In the face of such errors,
JSLint stops.

So there we have it. Don’t nest your comments.

This article is one of a series on the error and warning messages produced by JSLint.

, ,

When referring to function arguments in JavaScript, we almost always refer to them by the name by which they were passed:

function foo(a) {
    var b = a;   //refer to the function parameter 'a',
    //....
}

However, there is an object representing these arguments to which we can refer. This is the arguments object.

This object provides us with some useful properties, which include .length and .callee. It also allows us to refer to the argument by position like so:

function foo(a) {
    var b = arguments[0];
}

It is this use of the arguments object that JSLint complains about. Variables are given names to identify what they are and what they mean. There are a valuable tool for writing self-documenting code, and referring to them in any other way makes little sense. You’re also relying on the argument being in a particular position. If you ever change the order of the arguments in the function definition, you’ll have to change the index by which you reference each argument.

Moreover, unless your variable name is longer than 12 characters, you will require  more keystrokes to refer to the arguments themselves. In addition to this, opimisers like GZip which can give variables and arguments shorter names for compression and obfuscation purposes are likely to skip over these instances, reducing the compression capability of your code.

Refer to this post on JavaScript arguments at seifi.org for more information on the arguments object.

Special thanks to this article at Programming Goodies for highlighting this as missing from my list of JSLint Errors.

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

, , ,

Principles

Most developers are have instilled within themselves certain fundamental core programming practices. Possibly the most famous of these is the DRY (Don’t Repeat Yourself) Principle, which states that duplication can lead to maintenance nightmares, poor factoring, and logical contradictions.

But as with many principles in programming, there are always trade-offs, and times where the rigorous application of a principle can be unhelpful and even counter-productive.

The counterpart to DRY is WET (Write Every Time), and there are scenarios where it makes sense to duplicate code, as described in the articles: Write Every Time Dilutes performance Bottlenecks and Beware The Share.

The JSLint Error

Another principle that is preached almost religiously is the efficient management of resources, and one strategy for doing this is to allocate any resources as late as possible, and  release them as early as possible. The use of block scoping is a particularly common key for achieving this.

This gives rise to code similar to the following:

var a = 1;
if (x === a){
    var b = 2; //'try' giving variable 'b' block scope
    //do other stuff
}

In languages such as C++, C# and Java the above convention would limit the scope and lifetime of the variable ‘b’ to the ‘if’ block.

JavaScript, however, has no block scoping, and any variables declared within a block will be ‘hoisted’ to the top of the nearest scope when the code is picked up by the compiler. This is either the nearest containing function, or global scope. In short, this will make them visible outside the originally intended scope.

JSLint is all about reducing bugs, and had the author of this StackOverflow question run their code through JSLint, then they may never have had to ask a question at all.

Adding (Pseudo) Block Scoping

If you really wanted to enforce scoping down at this level then the following convention might help:

var a = 1;
if (x === a){
    (function(){
        var b = 2; //give variable 'b' (pseudo) block scope
        //do other stuff
    }());
}

Here we’ve wrapped the code in an anonymous function, and invoked it immediately (thanks to the set of parens at the end).

But JSLint Stops Scanning

Yeah, sometimes it does.

I have tried to remain neutral in all my posts on JSLint messages to date. Here, however I am going to jump off the fence and offer a sentiment of bafflement.

JSLint deems some errors so serious that it immediately ceases scanning. For me this is understandable in the event that it encounters utterly unparsable code and literally cannot continue, however, I just don’t understand why it must stop dead with the following:

for (var x=0; x<10 x++){
    //do something
}

And it appears I am not alone. A very similar query posted on the JSLint GitHub repository failed to yield any explanation before the thread was closed.

Any ideas anyone?

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

, ,

Periodically, I check the JSLint update history on GitHub to see what’s going on, and what significant updates have been included.

So, imagine my surprise when I saw a simple one-line comment on a June 12, 2011 edit:

eqeq

I did a quick diff on the source code to see this following line added:

 //     eqeq       true, if == should be allowed

This means that you can now configure JSLint to ignore uses of ‘==’, where previously it would have insisted you should use ‘===’

At the time of writing it hadn’t been updated on the JSLint front page, however testing locally with the following yielded no ‘==’ related warnings:

    /*jslint eqeq: true*/
    var x = 0;
    if (x == 1) {
        alert("test");
    }

I always recommend that use the ‘===’ in this instance anyway, but I am aware of the differing opinions surrounding it. Ultimately, you can make your own decision (and it is ‘on’ by default so you have to opt-out).

, ,

In JavaScript all functions and variables are often ‘hoisted’ to global scope, effectively making them global variables. This is potentially bad, as the following demonstrates:

if (true) {
    var x = 0;
}

alert(x); //alerts "0"

Here, even though ‘x’ is defined in a block, it is given global scope, and hence accessible outside the block. (For a demo, see http://jsfiddle.net/vRmLL/)

If we define our variable within a function, however, the scope is retained within the function. So the following will not work:

function SomeTest() {
    var y = 0;
}

alert(y); //undefined – a scoped variable - just what we want!

So, by using functions we can introduce scoping into JavaScript:

(function() {
    var z = 0;
})();

alert(z); //undefined – just what we want!

The last () executes everything in the body of the anonymous function. This pattern is called a closure.

This is a very simplistic overview of them. A more comprehensive one can be found in Morris Johns’ article JavaScript Closures for Dummies.

, , ,