What are the Alternatives to eval in JavaScript?

I have a little bit of code that looks just like this:

function StrippedExample(i1, i2, i3, i4, i5, i6, i7, i8) {
    this.i = [];
    for (var i=1,j=0 ;i<9;i++) {
        var k = eval("i"+i);
        if (k > 0) {
            this.i[j++] = k;
        }
    }
}

FireBug profiler claims that second longest function is eval(), taking up to nearly 6% of the run time.

Everyone says eval is EVIL (as in bad) and slow (as I have found), but I can't really do anything else - the server simply pulls the data out the database and pushes to the browser.

What alternatives do I have? I could do the same as I am doing here on the server but that just shifts the burden higher up the chain. I can't change the database layout since everything hooks into those 8 variables and is a massive undertaking.

Answers:

Answer
function StrippedExample(i1, i2, i3, i4, i5, i6, i7, i8) {
    var args = [i1, i2, i3, i4, i5, i6, i7, i8]; // put values in an array
    this.i = [];
    for (var i=0,j=0 ;i<8;i++) { // now i goes from 0-7 also
        var k = args[i]; // get values out
        if (k > 0) {
            this.i[j++] = k;
        }
    }
}

The above code can be simplified further, I just made the minimal change to get rid of eval. You can get rid of j, for example:

function StrippedExample(i1, i2, i3, i4, i5, i6, i7, i8) {
    var args = [i1, i2, i3, i4, i5, i6, i7, i8];
    this.i = [];
    for (var i = 0; i < args.length; i++) {
        var k = args[i];
        if (k > 0) { this.i.push(k); }
    }
}

is equivalent. Or, to use the built-in arguments object (to avoid having your parameter list in two places):

function StrippedExample(i1, i2, i3, i4, i5, i6, i7, i8) {
    this.i = [];
    for (var i = 1; i < arguments.length; i++) {
        var k = arguments[i];
        if (k > 0) { this.i.push(k); }
    }
}

Even if you weren't filtering the list, you don't want to do something like this.i = arguments because arguments is not a real Array; it has a callee property that you don't need and is missing some array methods that you might need in i. As others have pointed out, if you want to quickly convert the arguments object into an array, you can do so with this expression:

Array.prototype.slice.call(arguments)

You could use that instead of the var args = [i1, i2 ... lines above.

Answer

You are simply making an array from your function 8 arguments, removing the ones that are less than or equal to zero.

The following code is equivalent, and it will work for any arbitrary number of arguments:

function StrippedExample() {
  var args = [];

  for (var i = 0; i < arguments.length; i++) {
    if (arguments[i] > 0) {
      args.push(arguments[i]);
    }
  }
  //...
}
Answer
  1. Call the function with one argument — an Array
  2. Use the arguments object
Answer

One alternative to to pass an array to your function, instead of individual arguments:

StrippedExample([3, 1, 4, 1, 5, 9, 2, 6])

Then your code would be:

function StrippedExample(inArray) {
    this.i = [];
    for (var i=0,j=0 ;i<inArray.length;i++) {
        var k = inArray[i];
        if (k > 0) {
            this.i[j++] = k;
        }
    }
}

If you really need to pass in separate arguments, you can access them using your arguments array, which is an object that acts like an array (though it's not really; not all Array methods work on it) that exposes all arguments that have been passed in to your function; they do not even need to be declared in this case, but it's good form to include a comment indicating what sorts of arguments you are expecting for users of your code:

function StrippedExample(/*i1, i2, i3, i4, i5, i6, i7, i8*/) {
    this.i = [];
    for (var i=0,j=0 ;i<arguments.length;i++) {
        var k = arguments[i];
        if (k > 0) {
            this.i[j++] = k;
        }
    }
}

If you're guaranteed to only have 8 elements, then you could use 8 in place of inArray.length or arguments.length; I decided to use the more general version in my examples in case that was helpful to you.

Answer

Eval alternative:

exp = '1 + 1'
x = Function('return ' + exp)()
console.log(x)
Answer

This code should be made to use the arguments array that every Javascript function has access to.

It's not that eval is evil (it's in Lisp, so it must be good) it's simply a sign of a hack - you need something to work and you forced it. It screams out to me "The author gave up on good programming design and just found something that worked".

Answer
function StrippedExample() {

    this.i = [];
    for (var i=1,j=0 ;i<arguments.length;i++) {
        var k = arguments[i];
        if (k > 0) {
            this.i[j++] = k;
        }
    }
}
Answer

Given that there is a fixed amount of variables, you can build an array of them manually and loop through it. But if you have a variable amount of arguments, one way to get the variables passed to the function as an array is:

var args = Array.prototype.slice.call(arguments.callee.caller.arguments);

And your function would look like this:

function StrippedExample() {
    var args = Array.prototype.slice.call(arguments.callee.caller.arguments);
    for(var i in args) {
        if (args[i] > 0) {
            this.i[j++] = args[i];
        }
    }
}
Answer
  1. Short answer:
StrippedExample=(...a)=>a.filter(i=>i>0);

no need use eval for work with arguments at all.

  1. Initial code and most proposed solutions doesn't return result by traditional way.
Answer

definitely try this as a drop in replacement. I was looking for this answer and came to this post. I read the developer doc and this worked as a direct replacement in my application

var func1 = "stringtxt" + object + "stringtxt";

instead of ---> eval(func1); --> use --> Function(func1)();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Never_use_eval!

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.