0

When PHP is building HTML document, I add to it a code var myVariable = 'somedata';, which is used by a .js file. Of course, that file's code must be prepared for that variable not being set.

Doing some tests, I see that if I don't set the variable in HTML, Firebug console reports myVariable is not defined, and the code breaks: everything that should be run after the call to the function that uses that variable, doesn't run at all.

Only that function requires that variable, so I want the it to nicely return instead of breaking, so I used if(undefined === myVariable) return;, but it didn't work. Console still reports that error, and JS still breaks.

What's the best practice for testing if a variable is defined before using it?

Hikari
  • 3,797
  • 12
  • 47
  • 77

1 Answers1

5

Check the type of your variable instead:

if (typeof myVariable === "undefined")
WheretheresaWill
  • 5,882
  • 7
  • 30
  • 43