Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

JavaScript: Getting rid of three JSHint errors

JavaScript: Getting rid of three JSHint errors


Please find below a snippet of my Node.JS server code:

// Define the user API
var API = {
    list: 'private',
    login: 'public',
    logout: 'private',
    add: 'admin',
    remove: 'admin',
    edit: 'admin'

// Attach API handlers
for(var label in API) {
    var denied = 'Permission denied';

    var wrapper = (function (label) {
        return function (req, res) {
            var permission = API[label];

            if(!req.session) {
                if(permission !== 'public') {
            } else if((permission === 'admin') && (req.session.rights !== 'Administrator')) {

            eval(label + '(req, res)');
    }(label));'/user/' + label, wrapper);

Basically, I have an API handler for each property in API, and I attach the handlers programmatically, dealing with permissions as appropriate. JSHint however really does not like this. I get three errors:

Line 29: eval(label + '(req, res)');
eval is evil.

Line 31: }(label));
Don't make functions within a loop.

Line 12: for(var label in API) {
The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.

How can this piece of code be improved to make JSHint happy? Are there other changes you would suggest to the code?

Problem courtesy of: Randomblue


I would recommend going through the options that make jslint less strict and setting these ( provided you understand the why ). Jslint is very strict and that is why it has options to make it less strict. The important thing is that you know why they were flagged and why it is OK ok for you to allow these things.

For example to allow eval use:

/*jslint evil: true */

Some use:

/*jslint plusplus: true */

as they find that ++ and -- cause them no problems with bug creation or readability.

jslint is used to bring attention to POTENTIAL pitfalls. If you understand them, you can go around them.

Solution courtesy of: user1637281


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

JavaScript: Getting rid of three JSHint errors


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription