Instructor: When you have deeply nested code like this,
it can be overwhelming if you look at this code.
Where should you start?
Well, you're going to see various ways
of slimming this down and making it cleaner
throughout this module
but one very efficient tweak,
which you can make in a lot of cases
is that you use so-called guards
and that you fail fast.
Now, what does this mean?
Take a look at this simple snippet.
We have a if check here
where we check whether an email includes a @ sign
and if that's the case,
we do a bunch of work inside of that if statement.
And that bunch of work could be multiple lines of code.
It could be as much as all the code you have here
in the outermost if statement.
So all this code here ultimately
is in this one if check here.
Now, if you have a case like this,
you often can use a guard,
which means you simply invert the if check,
for example, in this case, by checking for the opposite
with an exclamation mark.
So for the email not including the @ sign,
and this is JavaScript
but of course, you can do this in any programming language.
The exact syntax might just matter.
And then you do one important other thing.
You just return inside of that if statement.
And that means that you now use this if check
as a guard.
It runs before your main code runs
and if you make it into this if check,
so if some condition is not met,
in this case, if the email does not include a @ sign,
then you fail fast,
which means you return,
which in the context of a function means
that the code thereafter,
all the code after the if statement won't execute.
This is what makes this if statement a guard.
It guards the rest of the code.
If this condition is not met
because we fail fast, we avoid that the other code
will run at all.
And we had the same behavior on the left side
but there, the to be executed code was inside
of the if statement
and therefore, it was nested inside of it,
making it harder to read.
A guard is typically way easier to read
and to understand.
And you cannot just use that if you have one if statement,
which wraps all your other code.
You can also use a guard
if you have a nested if statement
in another if statement.
For example, let's say here.
hasPurchases.
We could also outsource this
and turn this into a guard where we fail fast
so that we then have two consecutive if statements
instead of one deeply nested one.
And this is a super efficient technique
for removing unnecessary nesting.
Now, let's apply it to our example.