checking Object is possibly 'null' or 'undefined' [duplicate] - javascript

This question already has answers here:
Javascript test ( object && object !== "null" && object !== "undefined" )
(11 answers)
Closed 3 years ago.
I have this piece of code where I check if hostel.country.address is null but nevertheless
return hostel.country.address &&
hostel.country.address.internalEmployeeIdentifier !== null ||
hostel.country.address.externalEmployeeIdentifier !== null;
I have this compilation problem on
hostel.country.address
Object is possibly 'null' or 'undefined'.
- error TS2533: Object is possibly 'null' or 'undefined'.

return hostel.country.address &&
hostel.country.address!.internalEmployeeIdentifier !== null ||
hostel.country.address!.externalEmployeeIdentifier !== null;
should work.
Good luck

Please try this
const address = hostel?.country?.address
return address?.internalEmployeeIdentifier !== null || address?.externalEmployeeIdentifier !== null

You can use optional chaining (you should install the babel plug in)
and then your code will be something like:
hostel?.country?.address
more information can be found at:
https://github.com/tc39/proposal-optional-chaining
https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
installation:
https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining#installation
settings .babelrc
{
"plugins": ["#babel/plugin-proposal-optional-chaining"]
}

Add something like this, then modify your return line to use it:
function isValid(test) {
return !(test === null || test === undefined);
}
Your return could look like:
return isValid(hostel) &&
isValid(hostel.country) &&
isValid(hostel.country.address) &&
(isValid(hostel.country.address.internalEmployeeIdentifier) ||
isValid(hostel.country.address.externalEmployeeIdentifier));

When you have nested properties and parent property may or may not exist, it is good to take help of some external library. something like this can make it much simpler
const _ = require('lodash');
if(_.get(hostel, 'country.address.externalEmployeeIdentifier')) {
// do something
}
this way you do not need multiple && conditions. The library will take care of it.

One more way is to use object destructuring with default values.
const {
country: {
address: { internalEmployeeIdentifier, externalEmployeeIdentifier } = {}
} = {}
} = hostel || {};
return (
internalEmployeeIdentifier !== null || externalEmployeeIdentifier !== null
);

Related

Best way to address "cannot read property * of undefined"?

This error comes up a lot in javascript development.
cannot read property join of undefined
Is there a best way of dealing with this issue?
Some of the techniques I've used are:
Initialisation
question.tags = question.tags || [];
console.log(question.tags.join(', ');
If statements
if(question.tags) {
console.log(question.tags.join(', ');
}
You can use if..else, Object.hasOwnProperty(), Array.isArray() to determine if question exists and object has property tags and question.tags is an array
if (typeof question === "object"
&& question.hasOwnProperty("tags")
&& Array.isArray(question.tags)) {
//do stuff
} else {
// do other stuff, e.g
// question = {};
// question.tags = [];
}
There is no specific and exact way to do it. If there is an instance of the Array or Object or String, it inhertits the prototypal functions. Like an instance of array has a splice(), String instance has a replace ().
Now when this instance is undefined, it throws JS error. Lets assume a is supposedly an array. You can put a dirty check either by a logical ||
(a || []).length;
or a if block or a ternary property
return a ? a.length || undefined;
or a type check
(Array.isArray(a) || []).length
question.tags ? question.tags : []
You can use === and !== operators in if condition like
if(object.property !== undefined)
{
///write your code here
}
This operator will match your value + type so its easy to identify if mentioned property is undefined or not..hope this will help:)

Check if javascript object/property is defined

So i've read a handful of SO posts and some blogs, but still can't figure out why my code isn't working.
My code:
function myFunct(d) {
if (typeof d.parent.name == "undefined") {
console.log("undefined") ;} else { console.log("defined") ;}
}
d is an object that looks something like:
Object {
children: Object,
count: 676
}
I've tried using (!d.parent.name), hasOwnProperty, ===, and as above using typeof. Any suggestions?
The error I recieve is TypeError: d.parent.name is undefined
UPDATE:
Ok thanks everyone for the input, and my apologies if the question was confusing. I was actually looking for d.parent.parent but tried to simplify the question by using d.parent. I think the problem is that d.parent is not defined so it doesn't even get to d.parent.parent. Sorry for not being more specific!
If you want an undefined-safe check all the way down your object tree, you can use:
if( typeof( ((d || {}).parent || {}).name ) === 'undefined') {
}
If you have the luxury of having Lodash at your disposal:
var d = {
parent: {
name: "Joe"
}
};
if ( typeof (_.get(d, "parent.name")) === 'undefined' ) {
}
Try to check all children with logical OR
if (typeof d == "undefined" ||
typeof d.parent == "undefined" ||
typeof d.parent.name == "undefined") {
// ...
}
if(typeof x === 'undefined')
Use this, it checks for type as well as value, thats what you need.
I believe the error is the property identifier parent. Are you sure your object has the property? The identifier d may be invalid because parent doesn't exists.

A simple way to see if a complex object variable (objectVar.some.other.value) is defined

My code is getting really quite polluted with:
if( typeof( objectVar ) === 'object' && objectVar !== 'null' )
if( typeof( objectVar.other ) === 'object' && objectVar.other !== 'null' )
// OK, objectVar.other is an object, yay!
}
}
This is a little ridiculous. I am after a function that reads like this:
isProperObject( objectVar.other );
Considering that if objectVar is not defined, this will actually fail miserably, maybe I should do instead:
isProperObject( 'objectVar.other' );
Then the function could eval() it. But no! It cannot do that, because isProperObject() would be in a different scope, one without objectVar.
So, it could be:
isProperObject( objectVar, 'other' )
OK this could work. Is there a function like this that is actually commonly used?
Your checks are needlessly verbose. You can do this instead:
if (objectVar != null && objectVar.other != null) {
// OK, objectVar.other is an object, yay!
}
This will check for both null and undefined, and so gives you the safety you need.
Or if you really need .other to be an object:
if (objectVar && typeof objectVar.other === "object") {
// OK, objectVar.other is an object, yay!
}
Also, you should have been testing for:
!== null
instead of:
!== 'null'
A different, novel approach is this:
if((objectVar || {}).other != null) {
Move to a "higher level" of programming and initialize values to a null or empty object.
You should be working with top- and intermediate-level objects which are initialized to usable values, and you thus know to exist. Only the "leaf" objects should potentially be in empty/ null state.
For example, instead of:
var dialogTitle;
var dialogId;
var dialogElement;
Prefer to build a valid container object, in an "empty" state.
var dialog = {
title: null,
id: null,
element: null
};
You can also use if (dialog.id != null) or, when you're not expecting false or 0 values, if (dialog.id).

JavaScript check if property defined [duplicate]

This question already has answers here:
What's the simplest approach to check existence of deeply-nested object property in JavaScript? [duplicate]
(7 answers)
Closed 10 years ago.
What is the recommended way to check if an object property like obj.prop.otherprop.another is defined?
if(obj && obj.prop && obj.prop.otherprop && obj.prop.otherprop.another)
this works well, but enough ugly.
The most efficient way to do it is by checking for obj.prop.otherprop.another in a try{} catch(exception){} block. That would be the fastest if all the remaining exist; else the exception would be handled.
var a = null;
try {
a = obj.prop.otherprop.another;
} catch(e) {
obj = obj || {};
obj.prop = obj.prop || {};
obj.prop.otherprop = obj.prop.otherprop || {};
obj.prop.otherprop.another = {};
a = obj.prop.otherprop.another ;
}
Not saying this is better but ...
x = null
try {
x = obj.prop.otherprop.another;
} catch() {}
// ...
Or alternatively ...
function resolve(obj, path) {
path = path.split('.');
while (path.length && obj) obj = obj[path.shift()];
return obj;
}
x = resolve(obj, 'prop.otherprop.another');
... but I guess the actual answer is that there isn't a best-practice for this. Not that I'm aware of.
If you're in a silly mood, this would work:
if ((((obj || {}).prop || {}).anotherprop || {}).another) { ... }
But I don't know if initializing three new objects is really worth not having to repeatedly type out the path.

is there something like isset of php in javascript/jQuery? [duplicate]

This question already has answers here:
JavaScript isset() equivalent
(28 answers)
Closed 6 years ago.
Is there something in javascript/jQuery to check whether variable is set/available or not? In php, we use isset($variable) to check something like this.
thanks.
Try this expression:
typeof(variable) != "undefined" && variable !== null
This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.
You can use it like this:
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
JavaScript isset() on PHP JS
function isset () {
// discuss at: http://phpjs.org/functions/isset
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: FremyCompany
// + improved by: Onno Marsman
// + improved by: Rafał Kukawski
// * example 1: isset( undefined, true);
// * returns 1: false
// * example 2: isset( 'Kevin van Zonneveld' );
// * returns 2: true
var a = arguments,
l = a.length,
i = 0,
undef;
if (l === 0) {
throw new Error('Empty isset');
}
while (i !== l) {
if (a[i] === undef || a[i] === null) {
return false;
}
i++;
}
return true;
}
typeof will serve the purpose I think
if(typeof foo != "undefined"){}
If you want to check if a property exists: hasOwnProperty is the way to go
And since most objects are properties of some other object (eventually leading to the window object) this can work well for checking if values have been declared.
Some parts of each of these answers work. I compiled them all down into a function "isset" just like the question was asking and works like it does in PHP.
// isset helper function
var isset = function(variable){
return typeof(variable) !== "undefined" && variable !== null && variable !== '';
}
Here is a usage example of how to use it:
var example = 'this is an example';
if(isset(example)){
console.log('the example variable has a value set');
}
It depends on the situation you need it for but let me break down what each part does:
typeof(variable) !== "undefined" checks if the variable is defined at all
variable !== null checks if the variable is null (some people explicitly set null and don't think if it is set to null that that is correct, in that case, remove this part)
variable !== '' checks if the variable is set to an empty string, you can remove this if an empty string counts as set for your use case
Hope this helps someone :)
Not naturally, no... However, a googling of the thing gave this: http://phpjs.org/functions/isset:454
http://phpjs.org/functions/isset:454
phpjs project is a trusted source. Lots of js equivalent php functions available there. I have been using since a long time and found no issues so far.
The problem is that passing an undefined variable to a function causes an error.
This means you have to run typeof before passing it as an argument.
The cleanest way I found to do this is like so:
function isset(v){
if(v === 'undefined'){
return false;
}
return true;
}
Usage:
if(isset(typeof(varname))){
alert('is set');
} else {
alert('not set');
}
Now the code is much more compact and readable.
This will still give an error if you try to call a variable from a non instantiated variable like:
isset(typeof(undefVar.subkey))
thus before trying to run this you need to make sure the object is defined:
undefVar = isset(typeof(undefVar))?undefVar:{};
Here :)
function isSet(iVal){
return (iVal!=="" && iVal!=null && iVal!==undefined && typeof(iVal) != "undefined") ? 1 : 0;
} // Returns 1 if set, 0 false
in addition to #emil-vikström's answer, checking for variable!=null would be true for variable!==null as well as for variable!==undefined (or typeof(variable)!="undefined").
You can just:
if(variable||variable===0){
//Yes it is set
//do something
}
else {
//No it is not set
//Or its null
//do something else
}

Categories