Index
ed
Search videos...
⌘
K
Search videos
Search across video titles, descriptions, and transcripts
Optional Chaining in JavaScript | Traversy Indexed
Back
Optional Chaining in JavaScript
Sep 4, 2025
intermediate
Quick Tip
Hide Transcript
0:00
So optional chaining in JavaScript is a
0:02
feature that lets you safely access
0:04
nested object properties without
0:06
crashing your app if something doesn't
0:07
exist. So let's take a quick look at an
0:09
example. We have a user object with a
0:12
name and email. But let's say it's
0:14
possible that they can have an avatar.
0:16
So I'm going to have a variable of
0:18
avatar URL. And I'm going to set that to
0:20
user.vatar
0:22
URL. And let's go ahead and save that
0:25
and try to log it and see what we get.
0:27
So you'll see that it throws a type
0:29
error. cannot read properties of
0:31
undefined reading URL. So basically I'm
0:34
trying to get this URL property from
0:36
this avatar property which doesn't
0:38
exist. It's undefined. Okay, it's not in
0:40
this user object. Now we have a couple
0:43
options. We could do a conditional which
0:45
could be a full if statement or we could
0:47
do a turnary and say if user.avvatar
0:51
then let's do user.avvatar
0:54
URL. Else then we'll say undefined. And
0:58
now if we clear this up and run it, then
1:00
I get undefined. It doesn't throw an
1:02
error because we're doing that check.
1:03
Now this is okay in this situation, but
1:05
it can get kind of messy if you're
1:07
dealing with multiple levels of
1:09
properties or you're getting multiple
1:11
properties. So what we can do is what I
1:13
just had, which was user.avvatar
1:16
URL. And the only thing we need to add
1:19
to it is the optional chaining operator,
1:22
which is a question mark. And I'm going
1:23
to put that right after avatar. Okay. So
1:26
now I no longer get the error. It's just
1:28
set to undefined. And you could go
1:30
multiple levels deep like maybe it's
1:32
under profile and you want to add the
1:34
optional chaining character there as
1:36
well and still get undefined. I don't
1:38
get any errors thrown.
Related Videos
1:38:36
React Native Crash Course 2026 - Build a Complete Mobile App
Apr 15, 2026
beginner
Crash Course
7:18
I Tried Vibe Coding - Here Are My Thoughts
Apr 28, 2025
intermediate
Quick Tip
43:53
Freelance Web Developer Roadmap
Mar 17, 2025
advanced
Other
3:03:29
React Native Crash Course+ | Build a Mobile App In 3 Hours
Feb 26, 2025
beginner
Crash Course