Richard Ayotte
Richard Ayotte

Reputation: 5080

Is there a way to avoid eval in this block of JavaScript?

Is there a way to avoid eval in this block of js?

// Check requirements Prototype and Scriptaculous
(function () {
 var requires = [
  'Prototype'
  , 'Scriptaculous'
 ]
 while (r = requires.pop()) {
  if (eval('typeof ' + r + ' == "undefined"')) alert(r + ' is required');
 }
} ());

Upvotes: 0

Views: 442

Answers (3)

Ivo Wetzel
Ivo Wetzel

Reputation: 46745

The eval here is completely pointless:

// since everything in the global scope gets defined on 'window'
typeof window[r] === 'undefined'; 

This will do the exact same thing, also note that r leaks into the global scope.

// Check requirements Prototype and Scriptaculous
(function () {
    var requires = ['Prototype', 'Scriptaculous'];

   var r = ''; // make sure to __not__ override a global r
   while (r = requires.pop()) {
       if (typeof window[r] === 'undefined') {
           alert(r + ' is required');
       }
   }
} ());

Upvotes: 3

mplungjan
mplungjan

Reputation: 177796

How about

if (typeof window[r] == "undefined")

Upvotes: 1

cdhowie
cdhowie

Reputation: 168988

 while (r = requires.pop()) {
  if (typeof window[r] == "undefined") alert(r + ' is required');
 }

Upvotes: 0

Related Questions