How to know where Optional Chaining is breaking?
Don't do the chain then. The chain is only interesting if you don't intend to stop. If you do, break it up at interesting spots - otherwise, where would you put in the code for the bad cases?
if let residence = john.residence {
if let address = residence.address {
...
} else {
println("missing address")
}
} else {
println("missing residence")
}
How does the JavaScript optional chaining(?.) operator works?
Its called "chaining" operator. It moves from left to right. if it sees ?.
it checks the left value if its undefined
. if yes, it returns undefined
and stops moving to the right. that means if b
is already undefined
it wont check the values on the right side
How to use optional chaining in Node.js 12
Optional chaining is currently not supported in Node.js version 13 and below. It will be supported from Node.js version 14 and most of the browsers as it is moved to Stage 4. Currently, few platforms are supporting it. You can find the list of platforms supporting optional chaining in the given link. You can enable optional using --harmony
flag.
optional chaining operator working on local host but not in production
It appears that your value that is expected to be the actual array is actually null or undefined. To prevent the error there are two courses of action you can take:
- ensure the array is never null or undefined (via default arguments or other means)
- use optional chaining syntax on the array itself:
const customFieldName = customFields?.[0]?.customFieldName || "Custom Field";
// ^ optional chaining added here
Regarding browser support, as long as you are using a proper babel configuration for the feature, or in your case create-react-app >=3.3.0, you should have no issues with browser support. Babel will just transpile the new syntax to valid, cross-browser code, like this:
var _customFields, _customFields$;
var customFieldName = ((_customFields = customFields) === null || _customFields === void 0 ? void 0 : (_customFields$ = _customFields[0]) === null || _customFields$ === void 0 ? void 0 : _customFields$.customFieldName) || "Custom Field";
How to chain attribute lookups that might return None in Python?
You might be able to use reduce
for this:
>>> class Foo(object): pass
...
>>> a = Foo()
>>> a.foo = Foo()
>>> a.foo.bar = Foo()
>>> a.foo.bar.baz = Foo()
>>> a.foo.bar.baz.qux = Foo()
>>>
>>> reduce(lambda x,y:getattr(x,y,''),['foo','bar','baz','qux'],a)
<__main__.Foo object at 0xec2f0>
>>> reduce(lambda x,y:getattr(x,y,''),['foo','bar','baz','qux','quince'],a)
''
In python3.x, I think that reduce
is moved to functools
though :(
I suppose you could also do this with a simpler function:
def attr_getter(item,attributes)
for a in attributes:
try:
item = getattr(item,a)
except AttributeError:
return None #or whatever on error
return item
Finally, I suppose the nicest way to do this is something like:
try:
title = foo.bar.baz.qux
except AttributeError:
title = None
Check for browser optional chaining support in Angular project
As I've already went with one of the options described in the question, I thought it would be good to answer it.
In my first attempt, I've tried the "third party library" solution, but it didn't work: when there's a syntax error (which is the case if we use optional chaining in a browser without support), the exception happens before the browser actually runs that code, leading to two results:
- The exception won't be caught in a try/catch block;
- The current "execution context" will end abruptly.
So, I needed a way to run the "checker code" in a separate context, in order to keep my main thread (and consequently, my app) from dying. Also, I needed a way to check if the code ran successfully or not.
The final solution I've come up with is a mix between two of the options: I've created a library which loads a simple script testing for optional chaining support, returning a Promise with a boolean indicating the browser's support.
The script is loaded dinamically, by adding a temporary script tag (which isolates the execution from the main context, preventing the SyntaxError from killing the app). In order to improve security, I've used the integrity attribute.
If anyone is going through the same issue, you can use my solution by installing the npm library optional-chaining-checker and following the instructions. I've tried to make it as customizable as I could, but if it doesn't attend your needs, feel free to check out my repository and adapt the code at will!
JS optional chaining clarification
Let's say you define variable like below
const variable = { value: 'test' };
then you want to access variable?.value
it equals variable === null || variable === undefined ? undefined : variable.value
.
Same with array.
Check typescript playground and see js output https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgJwXAnjAvDA2gXQNwBQBiyKA-AHRYCsADDkA
Optional Chaining in JavaScript returns undefined instead of null when the variable to be tested is null
An optional chain does not evaluate to the nullish value on which the property was accessed, but to undefined
- just like you get undefined
when a property does not exist in an object.
Conceptually, think of person?.street
not as
person && person.street
but rather as
(person ?? {}).street
Though accurately (especially when chained further, since it does short-circuit instead of evaluating the rest of the chain) it's really
person != null ? person.street : undefined
See also the FAQ on the optional chaining proposal:
Why does
(null)?.b
evaluate toundefined
rather thannull
?Neither
a.b
nora?.b
is intended to preserve arbitrary information
on the base objecta
, but only to give information about the
property"b"
of that object. If a property"b"
is absent froma
,
this is reflected bya.b === undefined
anda?.b === undefined
.In particular, the value
null
is considered to have no properties;
therefore,(null)?.b
isundefined
.
Related Topics
How to Hash a String to Sha512 in Swift
Add Datepicker in Uiactionsheet Using Swift
Swift Progress View with Nstimer
Is Dispatchsemaphore a Good Replacement for Nslock
What Might Be Causing This Animation Bug with Swiftui and Navigationview
How to Declare Protocol Property as Private
Prevent Error "Funk" Sound in Event Monitor Os X
How to Cast an @Binding in Swift
Deleting with One-To-Many Relationship
How to Rotate an Arkit 4X4 Matrix Around Y Using Apple's Simd Library
Nspopover to Start in a Detached State
Combined Chart (Line- and Bar Chart) Using iOS-Charts
Swiftui Sheet Not Updating Variable
"Use Default Container" Doesn't Show in Icloud Capabilities
Swiftui Tabbar: Action for Tapping Tabitem of Currently Selected Tab to Reset View
Swiftui 2 Pop to Root View with No Scene Delegate
Swift Protocol with Associated Type - Type May Not Reference Itself as a Requirement
How to Make High Score of Game to Be Saved on Leaderboard, with Swift