JSLint “eval is evil.” alternatives

I am have some JavaScript functions that run on both the client (browser) and the server (within a Java Rhino context). These are small functions – basically little validators that are well defined and don’t rely upon globals or closures – self-contained and portable.

Here’s an example:

  • Render without layout when format is JS (needs drying)
  • Javascript duplicate code detector?
  • jQuery drying up function
  • DRY - how to exchange this if-statement into less complex
  • Trying to understand DRY principles in Javascript
  • AngularJS: How to debug the 'App Already Bootstrapped with this Element' error
  • function validPhoneFormat(fullObject, value, params, property) {
        var phonePattern = /^\+?([0-9\- \(\)])*$/;
        if (value && value.length && !phonePattern.test(value))
            return [ {"policyRequirement": "VALID_PHONE_FORMAT"}];
        else
            return [];
    }
    

    To keep things DRY, my server code gets a handle on each of these functions and calls toString() on them, returning them to the browser as part of a JSON object. Something like this:

          { "name" : "phoneNumber",
            "policies" : [ 
                { "policyFunction" : "\nfunction validPhoneFormat(fullObject, value, params, property) {\n    var phonePattern = /^\\+?([0-9\\- \\(\\)])*$/;\n    if (value && value.length && !phonePattern.test(value)) {\n        return [{\"policyRequirement\":\"VALID_PHONE_FORMAT\"}];\n    } else {\n        return [];\n    }\n}\n"
                }
              ]
          }
    

    My browser JS code then takes this response and creates an instance of this function in that context, like so:

    eval("var policyFunction = " + this.policies[j].policyFunction);
    
    policyFailures = policyFunction.call(this, form2js(this.input.closest("form")[0]), this.input.val(), params, this.property.name));
    

    This all works very well. However, I then run this code through JSLint, and I get back this message:

    [ERROR] ValidatorsManager.js:142:37:eval is evil.

    I appreciate that often, eval can be dangerous. However, I have no idea how else I could implement such a mechanism without using it. Is there any way I can do this and also pass through the JSLint validator?

  • How to reuse beforeEach/afterEach in Jasmine JS?
  • DRY AngularJS Controllers for forms
  • Simplifying multiple boolean checks into a single one
  • What's the recommended way to extend AngularJS controllers?
  • jQuery - Another way to write this statement (DRY)
  • How to stay DRY when logic needs a C# and Javascript implementation?
  • 6 Solutions collect form web for “JSLint “eval is evil.” alternatives”

    I wouldn’t worry about it since you are only passing these function strings from the server to the client, and are thus in control of what will be evaluated.

    On the other hand, if you were going the other direction and doing the evals of client-passed code on the server, that would be an entirely different story…

    Update:

    As disabling the validation option in your comment may cause you to miss future errors, I would instead suggest passing the function name rather than the entire function and have the function library mirrored on the server and client. Thus, to call the function, you’d use the following code:

    var policyFunction = YourLibraryName[this.policies[j].policyFunctionName];
    var policyArguments = this.policies[j].policyArguments;
    
    policyFunction.apply(this, policyArguments); 
    

    Update 2:

    I was able to validate the following code with JSLint successfully, which essentially allows you to “turn off” validation for the vast minority of cases where eval is appropriate. At the same time, JSLint still validates normal eval calls, and all uses of this method should throw up flags for future developers to avoid using it/refactor it out where possible/as time allows.

    var EVAL_IS_BAD__AVOID_THIS = eval;
    EVAL_IS_BAD__AVOID_THIS(<yourString>);
    

    Dont encode a function as a string in JSON. JSON is for content, which you are confounding with behavior.

    Instead, I suppose you could return JS files instead, which allow real functions:

     { name : "phoneNumber",
        policies : [ 
            { policyFunction : function() {
                  whateverYouNeed('here');
              }
            }
          ]
      }
    

    But while that solves the technical issue, it’s still not a great idea.


    The real solution here is to move your logic out of your content entirely. Import a JS file full of little validation functions and call them as needed based on a dataType property in your JSON or something. If this functions are as small and portable as you say, this should be trivial to accomplish.

    Getting your data all tangled up with your code usually leads to pain. You should statically include your JS, then dynamically request/import/query for your JSON data to run through your statically included code.

    I would avoid using eval in all situations. There’s no reason you can’t code around it. Instead of sending code to the client, just keep it hosted on the server in one contained script file.

    If that’s not doable, you can also have a dynamically generated javascript file then pass in the necessary parameters via the response, and then dynamically load the script on the client side. There’s really no reason to use eval.

    Hope that helps.

    With very little parsing you could have had it like so:

    var body = this.policies[j].policyFunction.substr;
    body = body.substr(body.indexOf("(") + 1);
    var arglist = body.substr(1, body.indexOf(")"));
    body = body.substr(arglist.length + 1);
    var policyFunction = new Function(arglist, body);
    

    Which would provide a bit of validation, avoid the literal use of eval and work synchronously with the code. But it is surely eval in disguise, and it is prone to XSS attack. If the malevolent person can get their code loaded and evaluated this way – it will not save you. So, really, just don’t do it. Add a <script> tag with the proper URL and that would be certainly safer. Well, you know, better safe then sorry.

    PS. My apologises if the code above doesn’t work, it only shows the intent, I’ve not tested it, and if I made a mistake at counting parenthesis or some such – well, you should get the idea, I’m not advertising it by any means.

    You can use

    setInterval("code to be evaluated", 0);
    

    Internally, if you pass setInterval a string it performs a function similar to eval().

    However, I wouldn’t worry about it. If you KNOW eval() is evil, and take appropriate precautions, it’s not really a problem. Eval is similar to GoTo; you just have to be careful and aware of what you’re doing to use them properly.

    Well, the first thing to bear in mind is that jsLint does make the point that “it will hurt your feelings”. It’s designed to point out where you’re not following best practices — but code that isn’t perfect can still work just fine; there’s no compulsion upon you to follow jsLint’s advice.

    Having said that, eval is evil, and in virtually all cases there is always a way around using it.

    In this case, you could use a library such as require.js, yepnope.js or some other library that is designed to load a script separately. This would allow you to include the javascript functions you need dynamically but without having to eval() them.

    There are probably several other solutions as well, but that was the first one that came to my mind.

    Hope that helps.