Is there a shortcut to check nested property existence [duplicate] - javascript

This question already has answers here:
Null-safe property access (and conditional assignment) in ES6/2015
(11 answers)
JS checking deep object property existence [duplicate]
(2 answers)
Closed 6 years ago.
I dont know if a.b is set. I want to do something only if a.b[0].c is true. I can do something like this:
if (a.b && a.b[0] && a.b[0].c) {
// ...
}
Is there a shortcut to check nested existence? Can I simplify this kind of condition?

I used to code golf, and one of the tricks we used is the following.
(myArray || [])[0] || 0
First, myArray || [] is evaluated, if myArray exists, this returns it, if it doesn't, then it returns an empty array. Let's say myArray isn't defined. Next, the [][0] || 0 expression gets evaluated ans because [][0] is undefined, this returns 0.
In your case it could be used the following way:
((a.b || [])[0] || {}).c || {}
This returns an empty object if something's undefined.
I'm not saying you should use this (in fact, you shouldn't), I just want to show you, that there is a smaller solution.
Update:
If tc39 gets through, then you'll have a much better solution using optional chaining:
a.b?[0]?.c

Related

Checking for the existence of a javascript var inside an array that may or may not exist [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 16 days ago.
I'm trying to check to see if something exists in an array, let's say the array arr is:
{"targeting":{
"key1":"1",
"key2":"2"},
"session": "1234"
}
I want to check to see if arr.targeting.key1 exists so I do:
if (true === !!arr.targeting.key1)
This is true if it exists, but what if arr is empty? Then I get an error:
cannot read properties of undefined, reading 'key1'
What is the simplest way to check for the presence of arr.targeting.key1 that will just return false if arr.targeting or arr themselves are undefined?
Use optional chaining.
if (arr?.targeting?.key1)

JavaScript checking for nullish value as part of an if block? [duplicate]

This question already has answers here:
How can I determine if a variable is 'undefined' or 'null'?
(34 answers)
Closed last month.
Is it possible to check for nullish values as part of an if block, without resorting to a pair of explicit checks for null and undefined.
For example, don't want to do this:
if(key === null || key === undefined) {
// do something
}
This doesn't work, because it also includes other falsy values such as zero and empty array.
if(!key)
That's one of the good use cases of the operator ==:
if(key == null) {
// do something
}
This will work with both null and undefined, while keeping away other falsy values.

What is the difference in assigning a processed value directly to a variable and assigning without processing and then processed using && operator [duplicate]

This question already has answers here:
Access Javascript nested objects safely
(14 answers)
Closed 10 months ago.
I saw a function that receives a string parameter then performs some operations with it; like this:
const val = this.searchParam && this.searchParam.trim().toLowerCase();
My question is, why don't assign directly the processed string? Like this:
const val = this.searchParam.trim().toLowerCase();
I tried this in JS Bin to see if there's a difference, and the result is the same.
What do they exactly use the && operator?
In code snippet below, the first log writes undefined, the second throws an error:
searchParam = undefined
console.log(searchParam && searchParam.trim().toLowerCase());
console.log(searchParam.trim().toLowerCase());
Therefore, the result is not the same

Which is the better way to check undefined in Javascript? [duplicate]

This question already has answers here:
Detecting an undefined object property
(50 answers)
Closed 3 years ago.
I had been checking for undefined values myself like:
if(variable !== 'undefined')
then I came across the following code:
if(typeof variable1 !== 'undefined' || typeof variable2 !== 'undefined')
I followed the same convention knowing it's safer when variable goes undeclared. While in my code reviews, it was pointed I could simple write:
if(variable1 || variable2)
Which of these is the most standard way to check undefined?
There are various use case as following
if (variable) is standard way to check truthiness of any variable in javascript. You can examples of what values will be truthy on Truthy | MDN Web Docs. Also, Falsy | MDN Docs
The cases where you explicitly would check for undefined is when a variable has been declared but not assigned value or explicitly assigned undefined.
In that case use if (variable !== undefined).
If you are receiving response from an API which might consist of stringified value of undefined, which you are sure of, then only do the check if (variable !== 'undefined')

Best approach for determining if an object in reference is null [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
JavaScript, elegant way to check nested object properties for null/undefined [duplicate]
(4 answers)
Closed 5 years ago.
In JavaScript (or TypeScript), if I'm going to reference something like:
return myObj1.myObj2.myObj3.myProperty;
to be safe, I guard it with something like:
if (myObj1 && myObj2 && myObj3)
return myObj1.myObj2.myObj3.myProperty;
else
return null;
Is there a more concise way of just getting null from the above reference without surrounding it by an if?
Please note, since I'll be using this in a TypeScript app, some solutions may not work with dynamic object definition.
Thanks.
I'd use a library like lodash for this:
//gets undefined if any part of the path doesn't resolve.
const answer = _.get(myObj1, "myObj2.myObj3.myProperty");
//gets null if any part of the path doesn't resolve.
const answer2 = _.get(myObj1, "myObj2.myObj3.myProperty", null);
See https://lodash.com/docs/4.17.4#get for details.
You can define some temporary objects to substitute when a lookup fails.
return (((myObj1||{}).myObj2||{}).myObj3||{}).myProperty || null;
You can make a reusable object if desired.
const o = Object.create(null);
Then use it as needed.
return (((myObj1||o).myObj2||o).myObj3||o).myProperty || null;

Categories

Resources