Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a property of a sometimes null object without an error [duplicate]

Tags:

javascript

In javascript, I often want to access the attribute of an object that may not exist.

For example:

var foo = someObject.myProperty

However this will throw an error if someObject is not defined. What is the conventional way to access properties of potentially null objects, and simply return false or null if it does not exist?

In Ruby, I can do someObject.try(:myProperty). Is there a JS equivalent?

like image 985
Don P Avatar asked May 12 '14 16:05

Don P


People also ask

When to use optional chaining?

You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device.

How do you set all properties of an object to null?

To set all values in an object to null , pass the object to the Object. keys() method to get an array of the object's keys and use the forEach() method to iterate over the array, setting each value to null . After the last iteration, the object will contain only null values.

What is property of null?

null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.

What does it mean when an object is null?

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral ("null") behavior. The null object design pattern describes the uses of such objects and their behavior (or lack thereof).


2 Answers

I don't think there's a direct equivalent of what you are asking in JavaScript. But we can write some util methods that does the same thing.

Object.prototype.safeGet = function(key) {
    return this? this[key] : false;
}
var nullObject = null;
console.log(Object.safeGet.call(nullObject, 'invalid'));

Here's the JSFiddle: http://jsfiddle.net/LBsY7/1/

like image 197
Veera Avatar answered Oct 24 '22 01:10

Veera


If it's a frequent request for you, you may create a function that checks it, like

function getValueOfNull(obj, prop) {
  return( obj == null ? undefined : obj[prop] );
}
like image 36
Kornfeld Eliyahu Peter Avatar answered Oct 24 '22 00:10

Kornfeld Eliyahu Peter