Check if object exists in JavaScript
Asked Answered
T

20

370

How do I verify the existence of an object in JavaScript?

The following works:

if (!null)
   alert("GOT HERE");

But this throws an Error:

if (!maybeObject)
   alert("GOT HERE");

The Error:

maybeObject is not defined.

Tricotine answered 15/11, 2010 at 17:4 Comment(1)
The problem with this question is the use of the word 'exists'. What does 'exists' actually mean? An object can 'exist' but intentionally have no value (let myobj = null). In this case, accessing a property of the object causes a runtime error, which is what you're really interested in. So, while the accepted answer is technically correct and has a vast number of points, it's not of any practical value.Pigeon
G
697

You can safely use the typeof operator on undefined variables.

If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.

Therefore

if (typeof maybeObject != "undefined") {
   alert("GOT THERE");
}
Greeson answered 15/11, 2010 at 17:8 Comment(8)
if its always a string, you really could(should) do !== for the comparison.Hyaloid
Since this is a core Javascript feature, it is a shame that there is not a better and less error-prone built-in. The string comparison prevents the compiler from 100% reliably tell us when we made a small mistake (like a typo) in these kinds of checks.Antalya
in my case, im looking to SEARCH for this object, so this doesnt help. i want a solution i can use in console as wel, to see if object is in domtree somewhere without any clickery..Caudad
@T.J.Crowder Those examples don't seem to be accessible anymore.Crusade
@StefanvandenAkker: The link to the bad example should be jsbin.com/ibeho3/1. The good example was fine: jsbin.com/ibeho3/2. (Sadly JSBin redirects to the latest, and people have been editing that to within an inch of its life.)Cece
Curious as to why this was marked as the answer and has so many votes. I use some code suggested by @gblazex i.e. a method called existy which has the 1-line body foo != null . See the spec ES5 spec, clauses 11.9.3.2-3 ecma-international.org/ecma-262/5.1/#sec-11.9.3Flannery
+onefootswill note that this answer is from 2010. Also, it's one line. Additionally, null is not the same as being undefinedGreeson
@Hyaloid just because typeof always returns a string, we're safe to use the simple Not Equal comparison operator and not Strict Not Equal comparison operator. There is no point using the strtict one because in this case we'll always deal with a string value. Simple Not Equal operator != or simple Equal operator == are not always bad; there are use cases these can come to be really handy.Sensualism
S
50

There are a lot of half-truths here, so I thought I make some things clearer.

Actually you can't accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block).

The reason is Javascript has this notorious value of undefined which strikingly doesn't mean that the variable is not defined, or that it doesn't exist undefined !== not defined

var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)

So both a variable that exists and another one that doesn't can report you the undefined type.

As for @Kevin's misconception, null == undefined. It is due to type coercion, and it's the main reason why Crockford keeps telling everyone who is unsure of this kind of thing to always use strict equality operator === to test for possibly falsy values. null !== undefined gives you what you might expect. Please also note, that foo != null can be an effective way to check if a variable is neither undefined nor null. Of course you can be explicit, because it may help readability.

If you restrict the question to check if an object exists, typeof o == "object" may be a good idea, except if you don't consider arrays objects, as this will also reported to be the type of object which may leave you a bit confused. Not to mention that typeof null will also give you object which is simply wrong.

The primal area where you really should be careful about typeof, undefined, null, unknown and other misteries are host objects. They can't be trusted. They are free to do almost any dirty thing they want. So be careful with them, check for functionality if you can, because it's the only secure way to use a feature that may not even exist.

Shaquana answered 15/11, 2010 at 18:53 Comment(6)
Simply doing foo!=null will produce a ReferenceError if foo is not defined. Thus, it's better to use typeof, unless you're planning on catching the exception.Greeson
I write it down for you again: undefined !== not defined && foo != null can be an effective way to check if a variable is neither 'undefined' nor 'null'. I didn't say != null is good for checking if it exists. You're taking it out of context. (I also mentioned that it's a sidenote, not strictly related to the subject of the OP's question)Shaquana
You again confuse the term not defined with the type undefined. They are not the same. (note) it can be used !== you should use. Use common sense while reading. When the variable is declared (parameter list, or elsewhere) and you wanna check whether it's got a value, != null is completely safe. It's a different usecase than what the OP asked for, that's why I intruduced it as a note. The whole paragraph is about @Kevin's post and type coercion btw. As you can notice if you read carefully.Shaquana
@Greeson you're missing the part that you are not risking an error using != null when you know that the variable has been declared. This is very useful for checking function arguments, consider: var hasValue = function(foo) {return foo != null}Cheekbone
@Cheekbone that's true, but the entire issue is "How do I verify the existence of an object in JavaScript?". If you are certain it's been declared, that is a different situation.Greeson
I know it was stated in the answer, but I want to reiterate that "undefined" does not exactly mean "not defined." The snippet foo != null as a check amounts to (foo !== null && foo !== undefined), which will throw an exception if the variable has not been defined.Delegation
S
19

You can use:

if (typeof objectName == 'object') {
    //do something
}
Salivation answered 15/11, 2010 at 17:7 Comment(0)
M
18

Two ways:

typeof for local variables

You can test for a local object using typeof:

if (typeof object !== "undefined") {}

window for global variables

You can test for a global object (one defined on the global scope) by inspecting the window object:

if (window.FormData) {}
Macarthur answered 31/10, 2013 at 13:18 Comment(0)
A
9

If that's a global object, you can use if (!window.maybeObject)

Aymara answered 15/11, 2010 at 17:6 Comment(1)
I found window.hasOwnProperty('maybeObject') is a little more readable, if it's a global objectGynaecomastia
J
8

If you care about its existence only ( has it been declared ? ), the approved answer is enough :

if (typeof maybeObject != "undefined") {
   alert("GOT THERE");
}

If you care about it having an actual value, you should add:

if (typeof maybeObject != "undefined" && maybeObject != null ) {
   alert("GOT THERE");
}

As typeof( null ) == "object"

e.g. bar = { x: 1, y: 2, z: null}

typeof( bar.z ) == "object" 
typeof( bar.not_present ) == "undefined" 

this way you check that it's neither null or undefined, and since typeof does not error if value does not exist plus && short circuits, you will never get a run-time error.

Personally, I'd suggest adding a helper fn somewhere (and let's not trust typeof() ):

function exists(data){
   data !== null && data !== undefined
}

if( exists( maybeObject ) ){
    alert("Got here!"); 
}
Jordanson answered 15/7, 2019 at 18:9 Comment(2)
The first one already accomplishes the second. If it doesnt have a value it doesnt consider it to exist.Ferminafermion
@TS: not so; typeof null is object, as this answer says, for historical reasons. If you don't add the second test, you'll get a runtime error.Pigeon
R
6

You could use "typeof".

if(typeof maybeObject != "undefined")
    alert("GOT HERE");
Rock answered 15/11, 2010 at 17:10 Comment(0)
A
5

I used to just do a if(maybeObject) as the null check in my javascripts.

if(maybeObject){
    alert("GOT HERE");
}

So only if maybeObject - is an object, the alert would be shown. I have an example in my site.

https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes

Amphibole answered 19/11, 2010 at 11:27 Comment(2)
The problem is if maybeObject was not declared it will throw the Error: maybeObject is not definedPastore
if maybeObject is 0, 0.0, or "" , it checks to falseJordanson
H
5

The thread was opened quite some time ago. I think in the meanwhile the usage of a ternary operator is the simplest option:

maybeObject ? console.log(maybeObject.id) : ""
Highfalutin answered 11/4, 2019 at 17:10 Comment(1)
Yea, something along the lines of var maybeObject = typeof maybeObject !== "undefined" ? Chart:false; and check if not false.Petry
A
4

I've just tested the typeOf examples from above and none worked for me, so instead I've used this:

    btnAdd = document.getElementById("elementNotLoadedYet");
    if (btnAdd) {
       btnAdd.textContent = "Some text here";
    } else {
      alert("not detected!");
    }
Amygdalin answered 28/4, 2015 at 18:50 Comment(0)
P
1

Apart from checking the existence of the object/variable you may want to provide a "worst case" output or at least trap it into an alert so it doesn't go unnoticed.

Example of function that checks, provides alternative, and catch errors.

function fillForm(obj) {
  try {
    var output;
    output = (typeof obj !== 'undefined') ? obj : '';
    return (output);
  } 
  catch (err) {
    // If an error was thrown, sent it as an alert
    // to help with debugging any problems
    alert(err.toString());
    // If the obj doesn't exist or it's empty 
    // I want to fill the form with ""
    return ('');
  } // catch End
} // fillForm End

I created this also because the object I was passing to it could be x , x.m , x.m[z] and typeof x.m[z] would fail with an error if x.m did not exist.

I hope it helps. (BTW, I am novice with JS)

Polyadelphous answered 5/4, 2015 at 17:56 Comment(0)
B
1

for me this worked for a DOM-object:

if(document.getElementsById('IDname').length != 0 ){
   alert("object exist");
}
Bliss answered 14/8, 2017 at 15:12 Comment(0)
T
0
if (n === Object(n)) {
   // code
}
Triclinium answered 8/9, 2015 at 13:54 Comment(1)
While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others.Hexagonal
H
0

You could also try the && operator.

key && value

In this case if the key returns any value that is not:

  • null
  • NaN
  • 0
  • false
  • undefined
  • empty string ("" or '' or ``)

it will return key, else it will return value. In other words if the value is true (exists) it returns key else it returns value.

Herrmann answered 27/2 at 8:43 Comment(4)
This doesn't fully answer. In fact, you give a way to get the right object but not how to check itObsecrate
@Obsecrate so something along the lines of !value && alert("message")? would that be considered a check?Herrmann
It could be, but it's not the usecase of OP. Like you can only use this with something else, you can simply have a line like maybeObject && alert("GOT HERE"); It's not valid JS. Generally, we use this like obj = maybeObject && defaultObj(); for example, and IMO it's not what's your explaining/we can understand with your postObsecrate
That's actually a good point, I understand it now.Herrmann
K
0

You can use for if not exist any key or obj

 if (Object.keys(obj).length !==0){
      Whatever
 }

This verifies if Obj exist without any key, if you need to verify some existence key if (Object.keys(obj).includes('key'))

Kohima answered 3/4 at 3:3 Comment(2)
Object.keys(null) -> VM1216:1 Uncaught TypeError: Cannot convert undefined or null to objectKatharina
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewKatharina
D
-1

set Textbox value to one frame to inline frame using div alignmnt tabbed panel. So first of all, before set the value we need check selected tabbed panels frame available or not using following codes:

Javascript Code :

/////////////////////////////////////////
<script>

function set_TextID()
            {
                try
                    {
                        if(!parent.frames["entry"])
                            {
                            alert("Frame object not found");    
                            }
                            else
                            {
                                var setText=document.getElementById("formx").value;
                                parent.frames["entry"].document.getElementById("form_id").value=setText;
                            }
                            if(!parent.frames["education"])
                            {
                            alert("Frame object not found");    

                            }
                            else
                            {
                                var setText=document.getElementById("formx").value;
                                parent.frames["education"].document.getElementById("form_id").value=setText;
                            }
                            if(!parent.frames["contact"])
                            {
                            alert("Frame object not found");    

                            }
                            else
                            {
                                var setText=document.getElementById("formx").value;
                                parent.frames["contact"].document.getElementById("form_id").value=setText;
                            }

                        }catch(exception){}
                }

</script>
Doubledealing answered 13/9, 2013 at 6:21 Comment(0)
K
-1

zero and null are implicit pointers. If you arn't doing arithmetic, comparing, or printing '0' to screen there is no need to actually type it. Its implicit. As in implied. Typeof is also not required for the same reason. Watch.

if(obj) console.log("exists");

I didn't see request for a not or else there for it is not included as. As much as i love extra content which doesn't fit into the question. Lets keep it simple.

Kalvin answered 6/3, 2019 at 13:46 Comment(1)
I see a not in the question: if (!maybeObject) - but indeed, the title asks for the opposite.Klemens
T
-2
if (maybeObject !== undefined)
  alert("Got here!");
Tsushima answered 29/8, 2012 at 16:43 Comment(0)
R
-4

Think it's easiest like this

if(myobject_or_myvar)
    alert('it exists');
else
   alert("what the hell you'll talking about");
Reflect answered 19/4, 2014 at 14:32 Comment(0)
S
-11

Or, you can all start using my exclusive exists() method instead and be able to do things considered impossible. i.e.:

Things like: exists("blabla"), or even: exists("foreignObject.guessedProperty.guessNext.propertyNeeded") are also possible...

Sanderson answered 15/2, 2012 at 20:42 Comment(1)
And where is that method?Jordonjorey

© 2022 - 2024 — McMap. All rights reserved.