Functions
Functions are reusable blocks of code designed to perform a specific task or group of related tasks. While you can accomplish a lot without writing your own functions, they can help reduce redundancies and are crucial for some of the workflows in this class.
Declaring Functions
To use a cooking analogy... think of writing a function kind of like training a fellow cook on a recipe.
First, you would define and teach them the individual steps:
- Chop stuff.
- Sauté and simmer.
- Season to taste.
Then, in the future, you could simply ask: Can you please make some marinara sauce?
Start your function declaration with the function
keyword, followed by a name (using the naming conventions from our Style Guide), then parentheses and curly braces. The individual steps of your function go inside of the curly braces.
function makeSauce() {
console.log("Chop stuff");
console.log("Sauté and simmer");
console.log("Season to taste");
}
Function declarations can be placed anywhere, though I recommend putting them at the bottom of your script.js
file for consistency.
Calling Functions
Declaring a function does not actually execute the code inside the function. To run a function, call it using the function name followed by parentheses:
When using the console with embedded CodePen examples, you should open the Pen in its own window by clicking Edit On CodePen and then clicking the Console button in the CodePen editor.
See the Pen Function Declaration (IMS322 Docs) by Eric Sheffield (@ersheff) on CodePen.