JavaScript Functions
Suppose you are creating a website and it has a feature. For
instance, you might be creating a GPA calculator that makes it easy for people
to determine their GPA. You might have some input fields where the user enters
their courses, grades, and credit hours along with a submit button for the form.
Of course, you would want to add functionality to that button so that it would
output the user’s GPA once they press on it. Wouldn’t it be nice for you to be
able to simply send the courses, grades, and credit hours somewhere and get the
GPA back? This is exactly what functions are for: they allow you to write code
once and use it many times, and it makes your program more organized and modular.
Additionally, HTML already has an onClick attribute that you can add to buttons,
which allows you to tie functions to buttons.
This is how functions look like:
function func(parameter1, parameter2, parameter3) {
/* write code here */
}
Or, you can write it like this (the new way):
let func = (parameter1, parameter2, parameter3) => {
/* write code here */
}
Note that these functions do the exact same thing—they are
just different ways of writing functions. In both cases, func is the name of
the function and the parameters are fields where you can pass in any information
that you want the function to work with. If you wanted to call (or use) this function,
it would like something like this:
func(name, age, gpa);
In this case, name, and age are variables that we already
defined in our program. Functions can also use return statements, which returns
a value back to where the function was called.
Example:
function area(length) {
return length * length;
}
You can also use functions to assign values to variables
like this:
let x = area(4);
When working with functions, you must also consider scope.
Scope determines where your variables are defined in your program. For example,
you can have two variables named length like so:
let length = 0;
function area(length) {
return length * length;
}
Functions always use the variable that is most specifically
defined. So in this case, the variable that is in the function’s parameter is
the most specific to the function and that is what the function uses.
That has been the basics of functions in JavaScript! If you
would like to learn more about functions in JavaScript, here is a great resource: developer.mozilla.org.
Thanks for reading!
Comments
Post a Comment