Functions are the powerhouse in JavaScript. This is where the work happens. Do we need to calculate the space of a floor? This calls for a function.
function calculateFlooring(length, width) {
return length * width;
}
This function will calculate the flooring we need if we remodel the kitchen. So why do we need functions?
Benefits
Think of a function as a container for your code. Similar to a code block but, we can call this function repeatedly. This will facilitate reusable code.
In our prior example, you could copy the statement. Of course, if we wanted to change that we needed to search for that code and change all the occurrences.
Example
In our first function example, we calculated the flooring. Let’s step back and make it even easier. We can print something on the screen.
function greetTom() {
alert("Hello Tom!");
}
Of course, you can put your name in place of mine. If you want to keep the tradition, you can replace it with “Hello World”. Have you wondered why that is the tradition, look here.
Calling
The code may look nice but nothing happens if you don’t call it. How do you do that? I am glad you asked. Here is an example.
function greetTom() {
alert("Hello Tom!");
}
greetTom();
// do other things...
That call is easy as it takes no arguments. In our first function, we had two arguments we needed. Let’s try that next.
Passing arguments
In our first example, we started with a function to calculate flooring. It took two arguments.
function calculateFlooring(length, width) {
return length * width;
}
calculateFlooring(12,10);
We can pass in the two numbers to get the flooring needed. In this example, we hard-code the value. You won’t do that often or ever.
function calculateFlooring(length, width) {
return length * width;
}
calculateFlooring(length,width);
As you see here, we have the two arguments as variables. The names are the same as the function but don’t have to be.
Returning data
It is helpful when we return the calculation. If we don’t the function is not as useful as it could be. We just need to use the return. We did this in our calculate flooring function. Although we need to assign this or print it out.
function calculateFlooring(length, width) {
return length * width;
}
let totalFlooring = 0;
totalFlooring = calculateFlooring(length,width);
Now we can use this value later in the application. The prior examples didn’t use the value returned. This is always an option if you don’t need it later on.
Functions can do a lot for us. They provide us with a container for our code. Then we can call them and pass parameters. Along with that, they can return the data. If you need more information here is some further reading.