Functions

This YouTube video was created by Steve Griffith.

Functions are essential to programming. It's how we reuse common functionality. Once we define a function, we can use it as many times as we would like without needing to rewrite that logic. Functions are a very powerful way to speed up, organize and improve workflow. Let's dive right into them.

To begin, let's write our very first function. Anytime someone calls this function the computer will say hi. We can tell a function is being called by the () after the function name.

Function Parameters

We can pass in what are known as parameters to our function. In this example below, let's pass in a name so everytime this function is called the browser can say "hi" to specific things. In this example we set a function parameter of name and we pass in the argument "pluto" when we call it. This is really cool because now we can pass in different things to say hi to without rewriting our sayHi code. We say hi to pluto and saturn here.

Our functions can contain as many parameters as we define. In this example below we define a couple more parameters to capture additional information. In this example we say hi to our planets and describe their size.

One of the main benefits of functions are the ease of reuse. Here's a function we can can call to square a number.

Error checking and test cases are ways to help you identify specific things. Here, we set up a function highlightElement to outline any element we pass in.

Function Scope

Function Scope is the concept that variables declared inside fo a function are only accessible to that function add its children. Whereas variables declared outside of the function or block ARE accessible from inside the function.