How to check if a variable or object is undefined?

I always thought that I could just check undefined var by comparing it with undefined, but this is the error I get in the Chrome console:

enter image description here

How can I verify that the jQuery object is undefined?

EDIT:

enter image description here

if (jQuery) also causes problems.

EDIT:

decision:

if(window.jQuery) works. typeof(jQuery) == 'undefined' works too.

Can anyone explain why?

+6
source share
7 answers

There are several solutions:

  • Use typeof . This is a special operator and will never lead to a ReferenceError . It evaluates the value of "undefined" for, well, the value of undefined or for a variable that does not exist in context. I'm not a fan of this, but it seems very common.

  • Use window.jQuery . This forces a โ€œproperty searchโ€: property search is never interrupted and returns undefined if the specified property does not exist. I saw how it was used in some frameworks. Has a flaw in assuming context (usually window ).

  • Make sure the variable is "declared": var jQuery; if (jQuery) { /* yay */ } var jQuery; if (jQuery) { /* yay */ } . It does not seem very common, but it is quite true. Note that var is just an annotation and goes up. In a global context, this will create a jQuery property.

  • Catch a ReferenceError . Honestly, I have never seen this and do not recommend it, but it will work.

Happy coding.

+9
source

Process 1:

 if (jQuery) { // jQuery is loaded } else { // jQuery is not loaded } 

Process 2:

 if (typeof jQuery == 'undefined') { // jQuery is not loaded } else { // jQuery is loaded } 
+5
source

From here

 if(typeof jQuery == "undefined") { document.write("undefined"); }else{ document.write("Exists"); } 
+3
source

As far as I know, you can do

 if(typeof X == 'undefined') 

But there is a resource loader that you might want to take a look at. And the answer given before me is also true.

+2
source

A variable called "jQuery" in your code has never been declared, so it will throw an error, for example, "xxx (variable name) is not defined".

You can use the typeof operator to check if a variable is undefined or not

 if (typeof(jQuery) == "undefined") 
+1
source

You can use: if (typeof jQuery! == 'undefined')

or

Do what mozilla recommends

if ('jQuery' in the window)

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/undefined

0
source

if(jQuery) should be enough, right?

-1
source

Source: https://habr.com/ru/post/903893/


All Articles