Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 421
Yarin Avatar asked Nov 15 '10 17:11

Yarin


People also ask

How do you check if an object exists in JS?

Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.

How do you check if a key exists in an array of objects JavaScript?

Using the indexOf() Method JavaScript's indexOf() method will return the index of the first instance of an element in the array. If the element does not exist then, -1 is returned.


1 Answers

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"); } 
like image 53
JAL Avatar answered Sep 20 '22 01:09

JAL