1

Optional chaining is a powerful feature when it comes to access data like

const options = cache.[server]?.[channel]?.[service]

Now when writing data we generally need to do something like

cache[server] ??=  {}
cache[server][channel] ??= {}
cache[server][channel][service] = options

Is there something like optional chaining that make assignment like this lighter (maybe in one line)?

Something like :

cache[server]??{}:[channel]??{}:[service]=options

In this case adding {} or [] just after would permit to indicate what's expected to assign if nullish.


As proposed by @Bergi, the nearest way of doing this is to write like that:

((cache[server] ??= {})[channel] ??= {})[service] = options
8
  • There is in Coffeescript Commented Sep 25, 2020 at 11:56
  • cache[server]??{}:[channel]??{}:[service]=options - and this is what I call a readable, clean code Commented Sep 25, 2020 at 11:56
  • @kinduser The syntax could be improved, but it would still be better than a series of if statements that create all the intermediate objects. Commented Sep 25, 2020 at 11:58
  • @Justinas how is it called in Coffescript ? Commented Sep 25, 2020 at 12:01
  • @RolandStarke Can you show me an example ? Commented Sep 25, 2020 at 12:04

1 Answer 1

2

You can use parenthesis to transform the

cache[server] ??= {}
cache[server][channel] ??= {}
cache[server][channel][service] = options

into a single expression

((cache[server] ??= {})[channel] ??= {})[service] = options
Sign up to request clarification or add additional context in comments.

1 Comment

While it's not syntaxic sugar, it's the most modular way of doing what I asked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.