Js에서 선택적 체인 및 단락

작성자

카테고리:

← 피드로
DEV Community · Arun Prakash Pandey · 2026-08-09 개발(SW)

Arun Prakash Pandey

What is optional chaining?

In Js you can access properties of an object using ‘.’
or [‘property_name’]. For example:

let a = { b: 50 };
console.log(a['b']) // logs 50
console.log(a.b) // logs 50

Enter fullscreen mode Exit fullscreen mode

But there can be instances where the property does not exists or the value is null.
For example, In JavaScript, the values null and undefined are the only two values that do not have properties.
And when accessing properties of null or undefined will throw a Type Error. Like the below code:

let a = { b: null };
a.b.c.d
// => Uncaught TypeError: Cannot read properties of null (reading 'c')

Enter fullscreen mode Exit fullscreen mode

To gracefully handle such type errors, we use optional chaining.
Notice the use of ? in the below code.

let a = { b: null };
a.b?.c.d
// => undefined

Enter fullscreen mode Exit fullscreen mode

a is an object, so a.b is a valid property access expression. But the value of a.b is null, so a.b.c would throw a TypeError. By using ?. instead of . we avoid the TypeError, and a.b?.c evaluates to undefined.

What is short circuiting?

The term short-circuiting generally refers to an electric short circuit, which means that the electric current took a short-cut to reach at a particular point rather than taking the intended path.
Here in Js, it has a similar intention.
Let’s understand through a code example:

let a = { b: null };
a.b?.c.d // undefined

Enter fullscreen mode Exit fullscreen mode

(a.b?.c).d // Type Error

Enter fullscreen mode Exit fullscreen mode

Note that the first code block is (without the parenthesis)
simply evaluates to undefined and does not throw an error. This is because property access with ?. is “short-circuiting”
i.e. immediately reaching to the final result instead of following the intended property access.
Where as the second code block will be evaluated entirely no matter what.

If the subexpression to the left of ?. evaluates to null or undefined, then the entire expression immediately evaluates to undefined without any further property access attempts. Hence, the code block short circuited.

Next, we will look into conditional method invocation.
Thank you for reading my blog, any suggestions / comments / likes / dislikes are appreciated.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다