The war of good vs. $eval (or eval vs. $eval)

Eval… the ultimate bane. Nothing can be said that wasn’t said before.  The bottom line is – stay away from it.  Ok, so you don’t know why it is bad for mankind (or JS apps)? Do you know what’s it good for?

Let’s start from the good stuff – why use eval?  Let’s say you have a very complex object:

var myObj = {
  level1: {
    level2: {
      level3: {
        level4: {
          level5: 5
        }
      }
    }
  }
}

Now you have this function:

function accessObjectPropery(property){
  return myObj[property];
}

Let’s say the user sends you ‘level1.level2.level3’.  The functino wouldn’t work.  But using eval can solve this issue:

function accessObjectPropery(property){
  return eval('myObj.' + property);
}
  1. Security issue – someone can inject a code that would be eval‘d and then executed…
  2. Performance – no optimization until runtime, caching issues – you name it.
  3. Bad architecture – debugging becomes a mess…

These are the 3 major issues mentioned over the web. You can look for more and post below.

Ok, now to the point – this is an angular post, and there’s a $ sign in the title, so this means angular has some solution for us, right?

Angular’s $scope has a very powerful function that’s called… $eval.  Now, this function works much like the (bad) old eval, only it is good 🙂

In short, instead of this:

 eval('myObj.' + property);

Use the angular $eval:

$scope.$eval(property, myObj)

Same result, much faster and much safer.  That’s not all… the original intention of the $eval function is to get properties out of the $scope itself.  This means, that if you do not add myObj as a variable to the function, the property will be searched for in the calling $scope.  When is it most useful? When you want to get a $scope property in a directive that doesn’t have an isolate scope:

Leave a Reply