-1

I know that Javascript's eval can evaluate expressions like

(true) && (false)
(true) || (false) 
 etc.

However, does the specification of eval include evaluating statements involving unknowns like

(true) && (null)
(true) || (null)
(null) && (null)
(null) || (null)
 etc.

I have tried this in code and seen that it does it, but is this expected behavior? Do the Javascript eval specifications say this?

CodeBlue
  • 14,631
  • 33
  • 94
  • 132

3 Answers3

2

Does Javascript eval correctly evaluate tri-state boolean logic?

Define "correct". Javascript defines the behavior. Eval in Javascript evaluates the string as a javascript code. SQL defines the behavior as well. The behavior is different in both.

In javascript, null acts like false in boolean expressions (is falsy).

0, NaN, "", null, undefined (and of course false) are all falsy. Objects, non-empty strings and non-zero numbers (and of course true) are all truthy.

&& returns the first falsy argument (if any) or the last argument (lazy AND) and does not evaluate the rest. null && "anything" is null. This can be used in statements like console && console.log && console.log().

|| returns the first truthy argument (if any) or the last argument (lazy OR) and does not evaluate the rest. null || "something" is "something". This can be used in statements like var xhr = XmlHttpRequest || ItsReplacementInOlderBrowsers

!null evaluates to true. if(null) ... evaluates the else branch. The same applies to anything falsy.

Technically, undefined variables are undefined, not null. Both are falsy, though.

John Dvorak
  • 26,799
  • 13
  • 69
  • 83
0

null evaluates to false, but keep in mind that there are more details involving null (eg: the use of ===).

Please check out this page. It covers this in more detail: http://www.mapbender.org/JavaScript_pitfalls:_null,_false,_undefined,_NaN

RonaldBarzell
  • 3,822
  • 1
  • 16
  • 23
0

null is not "unknown", when placed as an operand in a comparison it is simply coerced to a boolean (false). See the row for null in this "truthy table" for more information.

I don't believe there is any "specification" for behavior of eval - all it does it take a string representation of javascript and execute it as javascript in the current context. There is no reason that

eval('(true) && (null)');

would give you different results than

(true) && (null)

Also, eval is evil.

Community
  • 1
  • 1
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • `eval` executes in the current scope, not in the global scope. This answer sounds as if this wasn't the case. Note that the context in the specification refers to the `this` object. – John Dvorak Dec 12 '12 at 15:01
  • @JanDvorak right, i was thinking of `setTimeout`, i will edit. thanks. – jbabey Dec 12 '12 at 15:05