You can use optional chaining
Examples:
// Access Properties
user?.name; // user might be null/undefined
user.name?.firstName // user will be available however name is not guaranteed.
// Access array values
addresses?.[index]; // array addresses might be undefined
// May be function??
user.getGeolocation?.(); // If the function exists execute it.
Slightly unrelated but something around handling of null/undefined is another feature called Nullish coalescing operator ??
// Example:
function foo(input) // some Array as input {
//.. Some stuff
return [input??[]].concat(bar); //if input is empty ignore and concat bar on an empty array and return.
}
//----
const defaultVal="someVal";
...
const val = this.someObj.prop1??defaultVal;
Below is the outdated solution prior to Optional chaining became native to Javascript:
You can do this way, as there is no built in way of doing that:
var x = (user || {}).name;
- If user is not defined/null you will get undefined
- If user is defined you will get the name property (which may be set or undefined).
This won’t break the script if user is not defined (null).
But user variable has to be declared some where in the scope, even though its value is not defined. Otherwise you will get the err saying user is not defined.
Similarly if is in global scope then you can explicitly check for this variable as a property of global scope, to avoid the error as mentioned above
ex:
var x = (window.user || {}).name; // or var x = (global.user || {}).name;
For safe execution of functions,
var noop = function(){}; //Just a no operation function
(windowOrSomeObj.exec || noop)(); //Even if there is no property with the name `exec` exists in the object, it will still not fail and you can avoid a check. However this is just a truthy check so you may want to use it only if you are sure the property if exists on the object will be a function.