Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSLint "out of scope" error due to function ordering?

JSLint seems to be picky about function ordering.

This passes fine:

function a() {
    'use strict';
    return 1;
}

function b() {
    'use strict';
    a();
}

While this gives an 'a' is out of scope error message:

function b() {
    'use strict';
    a();
}

function a() {
    'use strict';
    return 1;
}

Is this by design? Should I care? How can it be avoided in larger (more complex) cases, where it might not always be possible to give the functions a clear order?

like image 505
Codemonkey Avatar asked Jan 05 '16 14:01

Codemonkey


Video Answer


2 Answers

JSLint/JSHint expect you to define functions before you reference them. However, JavaScript doesn't care because functions and variables are hoisted.

You can change your code style, or tell the linter to ignore it using http://jshint.com/docs/options/#latedef

/* jshint latedef:nofunc */
function b() {
    'use strict';
    a();
}

function a() {
    'use strict';
    return 1;
}

See https://stackoverflow.com/a/23916719/227299

like image 188
Juan Mendes Avatar answered Oct 20 '22 12:10

Juan Mendes


@epascarello's link to where this was discussed for JSHint really is absolutely essentially here, because this isn't just a question of style.

Let's hit the high points of the excellent answer at that question, as it applies to JSLint as well.*

There are two ways to define functions: Function declaration and function expression. The difference is annoying and minute, so let's just say this slightly wrong thing: If you're writing it like function name() {}, it's a declaration, and when you write it like var name = function() {} (or an anonymous function assigned to a return, things like that), it's a function expression.

bar(); //This won't throw an error
function bar() {}

foo(); //This **WILL** throw an error
var foo = function() {}

[emphasis mine -r]

It really is worth reading all of the answer there, but it's also worth emphasizing that this JSLint error isn't just about style, it's warning you about the possibility of a functional error. Edge-case-y, sure, but a useful habit.

I'll also add that there shouldn't be a case where you have to recursively call functions in JavaScript that exist before they're defined. I've been annoyed when I've seen this error in that context a few times, but it's [almost?] always helpfully shown some code smell where a refactoring was useful rather than a place where all the function jumping is required.

It seems like you might be able to cheat around the warning if you jump a lot with function namespacing, which I may have embarrassingly done in a case or two. I hope not (on both counts), though.


* I was tempted to add JSLint to that question and call this one a dupe, but wasn't sure that was quite kosher.

like image 29
ruffin Avatar answered Oct 20 '22 11:10

ruffin