The Expressions Cheat Sheet
Loading...

Functions are a big part of JavaScript and expressions. You may have even been using them without knowing.

Ever used wiggle() ? wiggle is a function written by people at Adobe.
It's a block of code that WILL do something, but only when you call it.

function yourFunctionName (argument1, argument2) {
  return
};

// your function won't run, unless you call it like so:
yourFunctionName()

From time to time you might encounter code where the function declaration exists AFTER the function has been called, like so:


yourFunctionName()

function yourFunctionName (argument1, argument2) {
  return
};

Code like this will still run just fine because function declarations are moved to the top of their scope before the computer runs the code. That process is called hoisting.

So this is the basic syntax for writing a function. You as a motion designer have the power to make the decision to learn more about this topic.
If you are interested in expanding your knowledge about functions check out this tutorial from W3Schools.

For now, let's focus on practical examples so we can get the hang of it quickly.

Create a function that multiplies a number by 2

this function takes a number and multiplies it by 2.

function multiplyByFucking2(input){
	return input * 2
}

// It won't run, unless we call it
multiplyByFucking2(10); // result: 20
multiplyByFucking2(5); // result: 10
multiplyByFucking2(30); // result: 60

Create a function that gets the comp center

This function gets the comp size and multiplies it by half.

function getTheFuckingCompCenter(){
	return [thisComp.width, thisComp.height] * 0.5;
}

// It won't run, unless we call it
getTheFuckingCompCenter(); // result in a 1080p comp: [960,540]

Check if keyframes exist

// this function will check if keyframes exist using the numKeys variable built into After-Effects. If the number of keys is bigger than 0, the answer is true.

function hasFuckingKeyframes(){
	return numKeys > 0
};

// It won't run, unless we call it
hasFuckingKeyframes(); // result: true or false

Here's a fun idea, let's use this function we have created to fix the built-in loopOut() function.
Using loopOut() will throw an error if keyframes don't exist. But now we can use our new function to check if keyframes exist before we use loopOut() at all.

 if ( hasFuckingKeyframes() ) {
	loopOut()
} else {
	value
}

Or in an even shorter form:

hasFuckingKeyframes() ? loopOut() : value;

Check if something is in view

if either dimension is smaller than 0 or bigger than its corresponding comp dimensions, it's outside the view.

function isInView(x,y) {
	// if x is outside the answer is false
	if (x < 0 || x > width) { return false }

	// if y is outside the answer is false
	if (y < 0 || y > height) {return false }

	// otherwise, the answer is true, it's in view
	return true
};

// It won't run, unless we call it
isInView(0, 20) // result: true or false, depends on the comp size