Skip to content

Additional syntax for safe navigationΒ #114

@EliteMasterEric

Description

@EliteMasterEric

I wanted to make a new home for a topic of discussion that is somewhat dispersed right now.

Safe navigation was implemented for object field access in 4.3.0, however it was not implemented for array access or function calls, despite being included in the original proposal #89 .

Array Access

The original proposal dictated that accessing nullArray?.[0] would return null, as opposed to nullArray[0] which currently throws a TypeError.

This syntax is notably useful in cases where you are working with nested arrays, like nullArray?.[i]?.[j]?.[k]. The fallback behavior is also very clear.

The syntax of ?.[] is used over ?[] since the latter is indistinguishable from a ternary operator by the parser. This syntax would notably be shared with Javascript and no other language.

Function Calls

The original proposal dictated that accessing nullFunction?.() would return null, as opposed to nullFunction() which currently throws a TypeError.

This syntax is notably useful primarily in the case where you are performing multiple object chaining operations in one line, such as object1?.object2?.myFunction?.(). It also may be used in the case where you use an optional callback function.

The main reasoning behind these not being implemented with the original proposal, as stated here: https://www.youtube.com/watch?v=lkpoTcHKjSE&t=454s

We didn't add the other variants, you sometimes see ?[ or ?( to make calls. We weren't sure if this was really needed, to me it looks kind of... it looks a bit awkward, and there might be use cases for it, but for now we decided to just stick to this one.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions