Optional chain call in javascript

Resources refer to fun fun fuction. Thank you!

const user = { name:'zideajang'}
const zip = user?address?.zip
console.log(zip)

I have seen this symbol in kotlin. Maybe there is a corresponding symbol in c ා. If we run it now, we will definitely report an error, even if we remove it? In fact, sometimes learning a new language doesn't have to be used immediately, or it won't be used in the future, but at least the new language opens a new door for us, we have more experience, and then integrate some good features of the language into our development.

This will be supported in javascript versions in the near future, but now we can also experience this feature.

Of course, we do this through logic,

const user = { name:'zideajang'}
const zip = 
    user &&
    user.address &&
    user.address.zip 
console.log(zip)

We can also do this. We should write code blocks like this without thinking.

const user = { name:'zideajang'}
const zip = 
    user 
        ?undefined
        : user.address
            ? undefined
            : user.address.zip
console.log(zip)

It's ok

onst user = { name:'zideajang'}
let zip
try {
    zip = user.address.zip
} catch (error) {
    zip = undefined
}

console.log(zip)

Of course, you can write a method to realize this function and start to build wheels.

function get(obj, ...props){
    const val = obj[props[0]]
    if(props.length === 1 || !val) return val
    const rest = props.slice(1)
    return get.apply(null,[val,...rest])
}

const user = { name:'zideajang'}
const zip = get(user,'address','zip')
console.log(zip)

We can also refer to the third-party library for implementation. This is the first time I have contacted ramda, and I'm going to study it later. It's also very easy to use.

const R = require('ramda');

const user = { name:'zideajang'}
const userWithAdress = { name:'zideajang',address:{zip:2019}}
// const zip = get(user,'address','zip')

console.log(R.path(['address','zip'],user))
console.log(R.path(['address','zip'],userWithAdress))

For the time being, we can't make an optional call like kotlin. After careful consideration, we finally use it

const zip = get(user,'address','zip')

This way or the best alternative chain call, which we hope to find in the new version? This chain calls the operator optionally, so we don't have to build our own wheels.

Tags: REST Javascript

Posted on Wed, 04 Dec 2019 06:16:00 -0800 by Davidc316