Defining Custom Functions

So we have seen this before, functions but what are they? A function is a piece of code that can be reusable and executes when called on. The structure/syntax is normally: function nameOfFunction(parameters) { //code }

So we can actually pass variables through and we can return something back as well.

We do so by passing variables through the parentheses.

And return a value by using the keyword return, usually at the end of the functions definition.

Here’s an example I wrote out to kind of relate the concept to something simple. We are defining a function that will add 2 numbers. We are accepting 2 numbers and then we are performing an action on the numbers. Lastly when we add those two numbers on line 11 the function will return back the value of that operation.

Later when we want use this function we will call it like this

Notice we pass the values 1 and 2 in the function call. To prove it worked the next line will have the console will print out the value of sum and then show the result of the return of the function we made add. Pretty cool, now we have a function made that we can reuse to add two numbers.

Leave a comment