What Are Functions and How To Use Them

Photo by Mike Hindle on Unsplash

What Are Functions and How To Use Them

I like to think of functions as ways for a developer to be able to do multiple things at multiple times but without a lot of effort.

Functions are pieces of code that do very specific things when called upon. When you make a function, you can use it anytime you'd like. In this way, they are very useful and have a lot of applications when creating a program. Keeping DRYness(Don't Repeat Yourself) to a minimum, keeps the amount of code lines down, and helps those reading your code afterward to read your code quickly and understand well what you intended. And bonus, when it comes to debugging, we can do that more efficiently since it also isolates pieces of code that may be causing a mishap.

One way we type a function in JavaScript is like so...

function exampleFunction() {
    console.log("This is an example of a function!");
}

We use the keyword name in JavaScript, function, to label the type of code block we are making. The next word in the above example, exampleFunction, is the name we chose for the code block. We can choose a variety of things, letters, numbers, underscores and dollar signs.

Next to the function name is a set of parentheses, these can contain any parameters or a way for you to add more information to be used in the code block. As seen above, you do not have to include parameters if they aren't needed for the code block you are creating.

Then comes curly braces, which hold the code block you want the function to run, in this example, we want the sentence, "This is an example of a function!", to appear in the console.

After we've decided what code block we want to run and the function name and any parameters we'd like to include, we get to use it. Now we must call it, think of it like this.

Let's say you have a friend that has all the things you need to make a cake, the ingredients, the recipe, even the cake platter and they are just sitting at home waiting for you to call them so they know when to start. If you never call them, they won't know when you are ready for them to make the cake.

So just like calling your friend on the phone to make and bake the cake, the function won't do anything unless you call it.

function exampleFunction() {
    console.log("This is an example of a function!");
}

exampleFunction();

In this example, you can see that we now call the function into play so it can run the code we have inputted into our function.

Here is a link you can look at to get more comfortable with functions and everything they can do. Enjoy!

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Functions