Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
This bit of syntactic sugar can reduce simple if / else conditionals to a single line.
This video doesn't have any notes.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Let's take a second look at the if else
statement we wrote in the previous video.
0:00
This is a very basic
if else statement that
0:04
we can actually turn into a single
line using the ternary if operator.
0:07
The ternary if operator is
a bit of syntactic sugar
0:11
that can greatly simplify
if else blocks like this.
0:15
I'll show you how it's used here.
0:19
The way we use this is to replace the if
and else along with their curly braces
0:21
with the question mark and
colon characters like so.
0:26
This is doing exactly the same
thing that the previous code did.
0:46
This will return a map location
if path step is less than
0:50
path.length otherwise it will return null.
0:55
The return keyword is not
part of the ternary if.
1:00
We could have assigned the result of
this expression to a variable instead.
1:03
Returning two different
values based on a condition,
1:10
is a very common coding pattern.
1:13
It's a good place to use
the ternary if operator.
1:15
In fact, you might see lots of places
you could use the ternary if operator
1:19
instead of using if else.
1:23
You need to use your judgment though.
1:25
Sometimes using this syntactic sugar
in places where it isn't obvious
1:27
why you're using it, can make code
more difficult to understand.
1:32
So only use it in cases where it's
very obvious why it's happening.
1:36
Part of the reason I'm
showing it here is so
1:41
that you can recognize it when you see
it in code you might read in the future.
1:44
Another good tip for
using it is to use parenthesis.
1:49
We don't actually need to
use parentheses here, but
1:53
i think it makes it more
obvious what the condition is.
1:56
You could also put parenthesis around
these other operands to clarify
2:00
the two different results.
2:04
Let's compile this just to make
sure we haven't broken anything.
2:08
So going to the console ncs
2:11
-out:Treehouse *.cs.
2:14
Looks like we do have a compiler error.
2:22
It says class struct or
interface method must have a return type.
2:24
Let's see here.
2:28
Path.cs, line 12.
2:29
Looks like I forgot to say that we
want to return a MapLocation here.
2:35
Let's try this again.
2:43
There we go, it all works.
2:46
It's a good thing we have
a compiler to help us out?
2:49
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up