JS Basics: Functions
Functions are a basic component in JavaScript. You can think of them as a little machine: they take inputs, do some computing, and then give you outputs. The power of developing revolves around building functions that accomplish our specific needs and can be called when we need them.
In JavaScript, a basic function looks like this:
function squareNumber(number) {
return number * number;
}
We create a function by using the word and then giving it a name. In this case, the function is named squareNumber
because its sole purpose to square any number that you pass in.
Our function takes one parameter or input. This is the word in between the parentheses after the function name. The name of your parameter can be anything, but it is best in the beginning to use words or abbreviations that refer to what the parameter represents. In this case, I’m going to pass a number into my function, so I’ve called the parameter number
.
Next, our function returns an output. This means that it’s going to give us a new value once it is done computing. In JavaScript, the *
represents multiplication, so the value returned is going to be the product of the number and itself. Remember: number
represents whatever number we pass into the function.
Now that our function is created, we need to call it using the following code:
squareNumber(2);// 4
We call our function by using its name and passing it an argument, which gives us the output of 4. Arguments are simply the values that we are passing into our function as parameters. It’s okay if you get argument and parameter mixed up for now.
When you pass an argument, it takes the place of the parameter in the original function. So you can think of our function call like this:
function squareNumber(2) {
return 2 * 2;
}// 4
Now that we’ve replaced our parameters with the argument 2
, you can see how the function will multiply 2 by 2, and then return the value 4.
There you have it: a basic JavaScript function!
Functions can have many parameters, or none at all. They can have names or remain anonymous. Sometimes they return values, strings, objects, arrays, more functions, or nothing at all. The power of functions is in their versatility.
W3Schools has a number of interactive examples for learning more about JavaScript functions. You can check them out here.
Happy coding!