JavaScript Loops and Try/Catch statements are great ways
to add advanced functionality to an expression.
A JavaScript loop is a powerful way of iterating through an expression or property values
to count, repeat an action, or search a series of elements until it finds a specific value.
The “for” loop’s primary function is to re-run a block of code for a specified number of times.
It’s best for counting or iterating through a series of elements.
The for loop starts with the word “for” and includes three optional statements,
separated by semi-colons, and wrapped in parentheses.
The first statement runs before the loop and initializes the loop’s variable used in the condition.
If you’re using an existing variable as the condition’s parameter and you’ve included it
before the for loop, you can omit the first statement and just add a semi-colon in its place.
The second statement, which the loop condition, is an equality statement that determines
if the loop will run during each iteration.
If the condition is met, it will loop one time and then check the condition again.
The third statement runs after the loop is finished with a single iteration.
It can increment a value during each iteration, allowing you to count
or limit the number of times an expression runs.
These three statements are followed by a set of open and close curly brackets
that contain the code block to be looped.
This for loop example runs through every single layer in your composition, adds the names
to an array, and then outputs that array as a text string.
The first line initializes an empty array, and then the for loop begins, starting at 0,
and then looping through the number of layers in the composition,
increasing the iteration after each cycle.
During each loop, a new array index is added to myArray that matches the layer number
of the current iteration.
It then takes the corresponding layer and adds the name as a text string.
Now, the layer index is actually the loop iteration plus 1,
because arrays are zero indexed but layer numbers start at 1.
Now, once the loop has cycled through every layer in the current composition,
myArray is then output using a slice method to remove the first two layers in the composition,
and the last layer which is Background.
Now, immediately after the slice method, the join method is included to convert the array
to a text string, and separates each array index with a line break.
And so, as you can see here, the for loop is most effective when you’re counting
or looping a set number of iterations.
This particular for loop is looking at the number of layers in the current composition,
which allows you to duplicate a Planet layer, rearrange it, or even rename it.
And the for loop is going to include this layer in the array,
and then add it to the converted text string.
A “while” loop is a more flexible form of the “for” loop, and does not loop based
on a set number of iterations.
Instead, it loops indefinitely while a specific condition is true.
The while loop is best for situations where you’re dealing with an unknown number of loops.
The while loop starts with the word “while” and includes a single statement,
wrapped in parentheses.
The single conditional statement is evaluated and determines if that loop iteration will evaluate or not.
If the condition is met, it loops one time before checking the condition again.
This loop is then followed by a set of open and close curly brackets
that contain the code block to be looped.
This while loop example gives the illusion of the expression having memory
and adds the value of this Slider Control as it increases over time.
Expressions only have access to current values and values at a specific point in time.
Using this method, you can calculate a value for, say, a custom speed control,
and move a layer based on its speed, rather than using position keyframes.
It’s great for scenes that need to reflect distance traveled according to its speed.
The first few lines of this expression declare variables for a slider control,
the comp's current frame duration, the distance and t variables.
Then, the while loop begins with a single condition that runs as long as t
is less than the current time.
This code is run one time for every frame between the beginning of the composition
and the current playhead's time.
Inside of the loop’s code block, the distance variable is incremented by the value of
the Slider Control at the evaluated time, multiplied by the frame duration.
As you can see, this method is using the += assignment operator, which is shorthand for
saying distance equals distance plus everything after the equals sign.
So this sounds and looks pretty complex, right?
Well, essentially, this statement gradually loops through every previous frame and accumulates
the change in the src variable’s value, which provides smooth and steady growth.
After this calculation happens, t is incremented by 1 frame and the entire loop runs again.
Once the loop’s condition is satisfied, or after it runs every frame
between the beginning of the composition and the current time,
the loop stops and it moves to the next line of the expression.
Now, this final line basically takes the position value in X, Y, and Z
and adds the distance traveled that we've calculated here to the X position.
So here we have the Rocket moving at 500 pixels per second, and the loop is calculating
that distance for every single frame.
Now, once the Rocket hits the 1 second mark, we start to slow down all the way to 0,
and then throughout this section between seconds 2 and 3, you'll see that nothing is being added
because the slider is set to 0.
But as soon as the Rocket hits the 3 second mark, you'll notice that the slider is now
being animated from 0 to 2000 pixels per second.
And so, from this point to the end of the composition,
the Rocket is moving 2000 pixels per second,
which is being evenly divided on every frame and applied incrementally to the distance variable.
So here's a quick note: this method actually increases the render time gradually
across the duration of your composition.
This is because every frame must calculate every previous frame before it to accumulate the value.
So at 10 frames in your composition, the distance variable is only being calculated 10 times
before it outputs the distance.
But if you travel to, say, 3 seconds, now that same expression has to run 90 times to get the same value.
So keep your composition times shorter than a couple of minutes for reasonable calculation.
The continue and break commands can skip a loop iteration or leave the loop and move
to the next part of an expression.
They're pretty useful when paired with a conditional statement inside of a loop.
To skip a single loop iteration, just add continue where you want the loop to skip from.
Maybe you want to skip even or odd iterations?
This can be done with an if statement at the beginning of the code block to determine
if a condition is met, instructing the current iteration to be skipped.
To break a loop and move on to the next part of an expression, just add the word break
at the exact point where you want the loop to stop.
When using a for loop to search for a specific layer or value,
you can break the loop once it’s found to avoid unnecessary loop iterations.
Just a note: the while loop may need a break command after a certain number of loops.
This avoids crashing After Effects with an infinite loop that never satisfies the condition.
Sometimes, an expression becomes unlinked from a property reference and creates an error.
The try...catch statement is a very useful expression for templates and complex projects
when trying to build fallbacks for these expression errors.
The statement will try to see if the input gives a valid output,
and then specifies a catch response if an exception is thrown.
Basically, try something and then do something else if the error occurs and it doesn't work.
The statement is started with the word try, followed by an open curly bracket.
After the bracket you can add a simple expression for the try statement to evaluate.
It will only be executed if no errors occur when it evaluates.
And, at the end of this statement, add a close curly bracket.
If an error does occur, the try statement passes to the catch statement.
This starts with catch, open parenthesis, err, for error, close parenthesis,
and an open curly bracket.
After this curly bracket is where you specify the fallback values that will be used instead.
And, finally, this is ended with a close curly bracket.
So, in this example, the statement checks to see if a checkbox control exists on the current layer.
If it does, try outputs a 1 or a 0 based on the checkbox state.
If it doesn’t exist, catch will output a fallback of 0.
It’s great for checking to see if an effect actually exists,
or for properties that may get unlinked by accident.
You can delete the Checkbox Control and the catch statement will output 0 as the fallback.
If the syntax is correct, this expression will never display an After Effects expression error.
We've arrived at the end of Lesson 506 Different Types of Loops & Try Catch Statements
If you enjoy this expressions course, consider purchasing the paid content.
It includes in-depth documentation, extra tutorial content, high definition videos,
and all the project files used in the training.
Your purchase will help to create more free courses like this in the future.