Optional object property access

 


Photo by Hannah Joshua on Unsplash

Options: they aren't just for day traders any more!

I just read a post by Dr. Axel Rauschmayer about null and undefined (link to article).  Here's a summary of some of the more interesting items about optional object property access and the nullish coalesce operator.

  • The ?. operator is equivalent to "if the property exists, return it else return undefined".
  • You can chain the ?. operator for nested objects: it will return undefined the first chance it gets.
  • The ?? operator is like the `or` operator (||) except that it only passes through null and undefined.
Examples:
The ?. operator is equivalent to "if the property exists, return it else return undefined".

let obj = { foo: 42 };

obj?.address
// undefined

obj?.foo
//42

You can chain the ?. operator for nested objects: it will return undefined the first chance it gets.
let users = [
    { name: 'Tom', address: { line1: '1234 Main St.', line2: { city: 'Austin', state: 'TX' } } },
    { name: 'Bob' },
];

users[0]?.address?.line2?.city
// 'Austin'

users[1]?.address?.line2?.city
// undefined
// note that this does NOT throw

The ?? operator is like the `or` operator (||) except that it only passes through null and undefined.
let x = false ?? 42;
// x === false

x = false || 42;
// x === 42

let y = undefined ?? 42;
// y === 42

y = null ?? 12;
// y === 12

Comments

Popular posts from this blog

A short guide to cross-site request forgery attacks

How is an application like a bride's outfit? - 1 minute read