Search code examples
javascripthtmlinline

JavaScript runtime error: 'variable' is undefined while checking to see if undefined


I have the following lines written with HTML and some inline JS:

 <% if (x !== undefined || x !== null) { %>
  <div> Foo </div>
 <% } %>

It produces this dynamic function code:

if (x !== undefined || x !== null) {...

As well as this error:

0x800a1391 - JavaScript runtime error: 'x' is undefined

Can anyone explain why this is happening?


Solution

  • In order for Javascript to compare the value of the x variable it must look it up; since it is not yet defined it throws an error message. This error is happening before the runtime even attempts to compare the value to undefined. It's a little bit of a chicken-and-egg problem.

    use typeof x === 'undefined' instead.