JavaScript Lesson 5: Functions

0
14

What are Functions

A function encloses a set of JavaScript statements. They can either be built into the JavaScript structure itself, or you can create your own! Functions are primarily used for code reuse, information hiding, and composition in addition to specifying the behavior of objects. Functions are here to make your life easier so it’s important to have a good understanding of what they are capable of!

The best way to gain a solid understanding of functions is to break down some examples. So let’s go out and break some down!

Simple, ineffective, and pretty much useless, but let’s talk about it anyways. First you will notice the keyword function. At the start of any function you need to let the browser know what it is. After the keyword, we have myFunction which is the name we chose to give it. Take note that right after the name are two parentheses with para1 and para2 enclosed inside. The two paras are parameters for the function.

Parameters

Parameters are pieces of data that you are passing to the function. They could be variables, strings, numbers, or any other data type. There could be 20 parameters for your functions or you can have none! Either way, there will be parentheses after the function name.

After the parentheses, notice the open bracket {. Between this opening bracket and the closing one is where all your code will go that pertains to the function. There is no limit to the amount of code lines you can have, just know that you need the closing bracket to close the function.

The return keyword ends the function and returns the value assigned to it.

Next Lesson

Next we will talk about JavaScript Events.

Leave a Reply