1252748
1252748

Reputation: 15372

Is it incorrect to use eval() within this function? Can I accomplish the same functionality without it somehow?

I'm trying to write a function I can use to test all for falsy values, keeping it concise since it will be run quite often serverside.

function is_falsy(val){
   val = eval(String(val).toLowerCase());
   return !!val;
}

I wonder if there's any way it could be done shorter, or what the possible negative implications of using eval() might be. JSBIN tells me it is "evil".

JSBIN

Upvotes: 0

Views: 70

Answers (3)

user2864740
user2864740

Reputation: 61875

Assuming that val is a string that represents a JavaScript literal then we can take advantage of the fact that the only false-y values in JavaScript are:

  • 0 (+ or -)
  • NaN
  • the empty string ('') or ("")
  • null
  • undefined
  • false

Thus, ignoring edge-cases (like 0.0) we could write it like so (a lower case can be performed as in the original code):

function is_falsey_literal (lit) {
  if (['""', "''", "null", "undefined", "false", "0", "NaN"].indexOf(lit) >= 0) {
    return true;
  }
  // Ideally there are more checks on numeric literals such as `-0` or `0.0`.
  return false;
}

If needing to check a full expression then eval may "work" and is likely more practical when compared to writing a full JavaScript-in-JavaScript parser. For instance, in the above, the input string of (void 0) will be "true" although it evaluates to undefined which is definitely not a truth-y value.

Of course, perhaps the original data can be written/consumed such that there is no need for such a construct at all ..

Upvotes: 5

xdazz
xdazz

Reputation: 160833

If you only want to test is falsy, then the below is enough.

function is_falsy(val){
   return !val;
}

If you want to test whether a string is falsy value like 'false', then

function is_falsy(val){
   try {
     return !JSON.parse(String(val).toLowerCase());
   } catch(e) {
     return false;
   }
}

Upvotes: 1

Pekka
Pekka

Reputation: 449415

There should never be any need to treat a string containing false or undefined as falsy. Doing so is inviting false positives (or false negatives) on possibly completely unrelated data.

Imagine what else would be treated as "falsy":

  • !true
  • !1
  • !!true

it's begging for mysterious bugs in your application further down the line.

The program flow should make sure that an undefined value actually arrives at your testing script as a literal undefined, not a string "undefined".

Upvotes: 2

Related Questions