简体   繁体   中英

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?

It's because you're trying to access a variable that has never been defined.

Example:

 'use strict'; console.log(x); 

You can check if a variable has been declared using the typeof operator :

 'use strict'; console.log(typeof x === 'undefined'); 

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.

Not totally sure what syntax <% [some javascript] %> is (Classic ASP?), but as an alternative, sniff if x exists on your global object.

Since you've tagged this html , your global object should be window . (In node, as an example, the global object is literally global .)

<% if (window.x) { %>
  <div> Foo </div>
<% } %>

And you're done.

You could also use the more verbose, but also more precise, code I think you intended in your post, so that if x is falsy but not null or undefined -- eg, 0 or "" -- it still trips the if .

Though I'm pretty sure you wanted an && in there, not an || . That is, as originally written, your condition will always evaluate true. If x is undefined , then it's by definition not null , and vice versa!

Here's the tweaked version...

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

variable x is not defined in your javascript code. Do a check with typeof operator.

typeof x=="undefined"

if if returns true then your variable x is not defined.

try this

<% if (!x) { %>
  <div> Foo </div>
<% } %>

!x will return true for an empty string, NaN, null, undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM