0

I see sometimes in JSX this being using ?.

For example

const featuredImageInfo = {
  url,
  // eslint-disable-next-line camelcase
  alt: image?.alt_text,
};

I get invalid token unless i remove the ?. What is it for?

CyberJ
  • 1,018
  • 1
  • 11
  • 24
  • 1
    It's the [optional chaining operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). – AKX Nov 11 '21 at 07:17
  • If I remember correctly, that `?` save you to don't get an error in format `image.alt_text not defined`, that means, you will not get an error until the variable has been filled ... – Milos N. Nov 11 '21 at 07:20

2 Answers2

1

This is called Optional chaining but not specific to JSX.

It is safe way to access the nested object properties even if an intermediate property doesn’t exist.

Optional chaining props?.value means if the property exist then get the value of that else assign undefined.

const z = {
  test: {
    key: "val"
  }

};

console.log(z.test.key);
console.log(z.test2?.key)
console.log(z.test2.key) // error

In the above example you can see while using optional chaining it logs undefined when property does not exist , without it , it throws error

brk
  • 48,835
  • 10
  • 56
  • 78
  • Interesting thank you! Is there a more traditional way to access object properties if intermediate property doesn’t exist? Without using `?.` – CyberJ Nov 11 '21 at 07:50
-1

it's called Optional Chaining;) https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html

jebbie
  • 1,418
  • 3
  • 17
  • 27