This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 6 years ago.
var how = $('how');
var id = $('myId');
if ((how != null && !how.value.blank()) || myId != null) {
return true;
} else {
alert('Error');
}
Is there an easier way to check for not null and checking if the value of that element is blank without having to do both != null and then calling value?
Since null is falsy, a slightly shorter version would be
if((how && !how.value.blank()) || myId != null) {
...
}
Note that the above code and your own snippet both assume that if how exists, it will have a property called value, and will throw an exception if this is not the case.
Related
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
);
This question already has answers here:
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
(47 answers)
Closed 4 years ago.
Why is this not possible?
var value = null;
if(value == (null || ""))
{
//do something
}
I would like to check a value if it is null or empty without using the variable over and over again.
Use !value. It works for undefined, null and even '' value:
var value = null;
if(!value)
{
console.log('null value');
}
value = undefined;
if(!value)
{
console.log('undefined value');
}
value = '';
if(!value)
{
console.log('blank value');
}
If we split the condition into its two relevant parts, you first have null || "". The result of that will be equal to the empty string "".
Then you have value == ""., which will be false if value is null.
The correct way to write your condition is value == null || value == "".
This question already has answers here:
Access Javascript nested objects safely
(14 answers)
Closed 4 years ago.
What is the right way of checking if a nested property exists?
if (openResult.notification) {
if (openResult.notification.payload) {
if (openResult.notification.payload.additionalData) {
if (openResult.notification.payload.additionalData.sensorOpenWarning) {
// now do sth with openResult.notification.payload.additionalData
}
}
}
}
Use try catch
var obj;
try{
console.log(obj.one.two.three.four)
}catch(e){
console.log("obj is undefined")
}
You can use this abbreviate form:
const prop2 = ((obj || {}).prop1 || {}).prop2;
Applied to your code would be:
const sensorOpenWarning = ((openResult || {}).notification || {}).payload || {}).additionalData || {}).sensorOpenWarning;
This question already has answers here:
Javascript check if object property exists, even when object is undefined
(4 answers)
Closed 6 years ago.
I have an variable, lets call it myNiceVar, I need to check myNiceVar value & length, myNiceVar variable is just undefined, which for JavaScript compiler this means the variable is defined but does not have any value yet
var myNiceVar;
if(myNiceVar.length){
console.log("I have value!");
}else{
console.log("I am empty");
}
Now JavaScript returns:
Uncaught TypeError: Cannot read property 'length' of undefined
How to check something like that and do not getting any error
You could check for typeof equals 'object' and if length is a key.
Do not forget to check for null first, because null is an object without properties.
var myNiceVar;
if (myNiceVar !== null && typeof myNiceVar === 'object' && 'length' in myNiceVar) {
console.log("I have value!");
} else {
console.log("I am empty");
}
Try this one
var myNiceVar;
if (myNiceVar !== null && typeof myNiceVar === 'object' && 'length' in myNiceVar) {
console.log("I have value!");
} else {...}
An item of type undefined (and it is a type) has no length property - only items of type string and array do. Therefore, as #redneb notes, extend your condition to check for a non-falsy value before checking length.
if (myVar && myVar.length) { ... }
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I test for an empty Javascript object from JSON?
var test= {};
var incidentReport = {
"place1": "n/a",
"place2": "n/a",
"place3": "n/a",
}
Above are the two ways my varible is going to look. Ive tryed doing the following code to test if its empty/looks like {}
if(test == "")
and tried
if(test == null)
also tried
if(!test)
Does anyone know where I am going wrong? Just a beginner to JavaScript and JSON. Is what I am doing considered back practice are there better ways to declare this empty?
Thanks for the support
Use JSON.stringify
var test= {};
if(JSON.stringify(test).length==2)
alert('null')
if(test == "")
checks if it is an empty string, so this won't work
if(test == null)
checks if it is null which is "similar" to undefined - this isn't the case
if(!test)
checks if it is a falsy value, this in not the case either.
You have to check if there exist child-elements (properties):
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) return false;
}
return true;
}
if ( isEmpty(test) ){...}
The very important point is the .hasOwnProperty() - this checks if it is a real property of the object and not only inherited through the prototype chain.
test here is an object. so you have to check if there are any prioperties/elements int his object. You can try something like below
var test= {};
function isEmptyObject(obj) {
// This works for arrays too.
for(var name in obj) {
return false
}
return true
}
alert("is this object empty?" + isEmptyObject(test));