Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.prototype function to test if it is defined / not null? [duplicate]

Tags:

javascript

I'm simply trying to avoid this

if(typeof myObject !== 'undefined' && myObject !== null)
{
   //safely use myObject  
}

so I tried this

Object.prototype.doesExist = function() {
    return (typeof this !== "undefined" && this !== null);
}

followed by

if(myObject.doesExist()){
   //safely use myObject
}

but of course the result is myObject is not defined

it understand why this doesn't work, but has anybody figured out a better way to accomplish what I'm looking for?

like image 470
stackoverfloweth Avatar asked Feb 21 '26 18:02

stackoverfloweth


2 Answers

As stated in the comments, null or undefined are not instances of an Object, so they won't inherit Object's prototype.

Solution 1: Use a static Object method, which is a functional, though not quite as clean, solution similar to what you were trying to do.

Object.exists = function(obj) {
    return typeof obj !== "undefined" && obj !== null;
}

if (Object.exists(myObject)) {
   // safely use myObject
}

Solution 2: Use instanceof if you know what type of object you're expecting. This is recommended if you will be accessing ClassName's interface inside your if statement.

if (myObject instanceof ClassName) {
    // safely use myObject
}

Examples:

function A() {}
var a = new A(), b;

> a instanceof A
true
> a instanceof Object
true

> b instanceof A
false
> b instanceof Object
false

> null instanceof A
false
> null instanceof Object
false

> undefined instanceof A
false
> undefined instanceof Object
false

I think that handles your use-cases

like image 169
Steven Moseley Avatar answered Feb 23 '26 06:02

Steven Moseley


Loose equality will achieve the desired result without monkey-patching although it requires some knowledge of javascript's semantics:

myObject == null; //true for null and undefined, false for all others

You can also use logical and as a guard operator:

if ((myObject != null) && myObject.someMethod && myObject.someMethod());

Obviously you could criticize the above for readability, but because javascript dumps everything into the same global namespace I'd be very careful about adding even static methods to Object.

like image 26
Jared Smith Avatar answered Feb 23 '26 08:02

Jared Smith