Monday, April 16, 2012

JSHint or JSLint

Heard the buzz about JSHint?

I too am not a big fan of an opinionated code quality tool, but one of the main reasons I am hearing of people using JSHint is that doesn’t force you to declare your variables at the top of a function.

While it is really annoying to have to do this, I remembered in reading Javascript the Good Parts that it is best practice – I just couldn’t remember why.

Then I ran across this post which provides a snippet of why.

var name = "Dan";

function getName(){
    console.log(name);
    var name = "Paul";
    return name;
}
var newName = getName();

You would expect that console.log(name) would print “Dan” but instead it will print ‘undefined.’ This is because the variable name is scoped to the function and though the value gets set later, it is declared and scoped to the entire function.

If your going to allow this – you need to understand the ramifications.

The counter argument is that declaring variables at the top is noisy and unintuitive, especially in loops.

No comments:

Post a Comment