[javascript] Check if object exists in JavaScript

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.

This question is related to javascript debugging variables null undefined

The answer is


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");
}

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>

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

_x000D_
_x000D_
    btnAdd = document.getElementById("elementNotLoadedYet");_x000D_
    if (btnAdd) {_x000D_
       btnAdd.textContent = "Some text here";_x000D_
    } else {_x000D_
      alert("not detected!");_x000D_
    }
_x000D_
_x000D_
_x000D_


You could use "typeof".

if(typeof maybeObject != "undefined")
    alert("GOT HERE");

You can use:

if (typeof objectName == 'object') {
    //do something
}

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...


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


for me this worked for a DOM-object:

if(document.getElementsById('IDname').length != 0 ){
   alert("object exist");
}

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.


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)


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) {}

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


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) : ""

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!"); 
}

if (n === Object(n)) {
   // code
}

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.


Think it's easiest like this

if(myobject_or_myvar)
    alert('it exists');
else
   alert("what the hell you'll talking about");

if (maybeObject !== undefined)
  alert("Got here!");

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to debugging

How do I enable logging for Spring Security? How to run or debug php on Visual Studio Code (VSCode) How do you debug React Native? How do I debug "Error: spawn ENOENT" on node.js? How can I inspect the file system of a failed `docker build`? Swift: print() vs println() vs NSLog() JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..." How to debug Spring Boot application with Eclipse? Unfortunately MyApp has stopped. How can I solve this? 500 internal server error, how to debug

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to null

getElementById in React Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? How to resolve TypeError: Cannot convert undefined or null to object Check if returned value is not null and if so assign it, in one line, with one method call How do I assign a null value to a variable in PowerShell? Using COALESCE to handle NULL values in PostgreSQL How to check a Long for null in java Check if AJAX response data is empty/blank/null/undefined/0 Best way to check for "empty or null value"

Examples related to undefined

Checking for Undefined In React Raw_Input() Is Not Defined How to resolve TypeError: Cannot convert undefined or null to object "undefined" function declared in another file? Passing Variable through JavaScript from one html page to another page Javascript - removing undefined fields from an object PHP How to fix Notice: Undefined variable: Undefined Symbols for architecture x86_64: Compiling problems Undefined or null for AngularJS PHP Notice: Undefined offset: 1 with array when reading data