JavaScript Functions
Function is an essential concept in JavaScript, and will be used a lot in your program. As you become more experienced with JavaScript, you'll start to notice that parts of your code are repetitive, and do the same thing over and over. So, if you find yourself writing the same exact code more than once, that's where a function can help you avoid duplicating code, and provide a way to group reusable code together to use, or call later at any point in the program.

Return a Value

We’ve know that functions can be used to finish some tasks, like changing HTML elements and CSS styles (+JavaScript Clicks: Functions). Now that we learned JavaScript variables, we can also use functions to deal with values.

Functions can give something back when they finish. This is called returning a value. To return a value from a function, use the return keyword, which creates what's called a return statement. It can be followed by a value that the function generates.

For example, we want to write a function to calculate the size of a square with a side length of 2, and use the return keyword to return the value:
let square = 2 * 2;
return square;
or simply combine these two lines into one:
return 2 * 2;

We can create a function like this:
function square() {
  return 2 * 2;
}
square();

return exits a function and sends a value back to the spot in the program where the function was called.

A function can have more than one return statement, but only ever run one based on a condition:
function square() {
  if ( big ) {
    return 100 * 100;
  } else if ( small ) {
    return 2 * 2;
  } else {
    return 0;
  }
}
square();

Pass Information Into Functions

Functions often need specific information to perform a task. In addition to getting information from a function, you can also send information to a function to change how that function works. These information (parameters) can be put inside the parentheses () after the function name.

With the previous example, we can only calculate a square with one side length. But functions are often used for different conditions—we can create a function to calculate the size of a square with any side length with a variable x, and pass any length we want to the function.

function square(x) {
  return x * x;
}
When we call the function, by putting different values (arguments) in the (), it will return different results:
square(2); // return 4
square(100); // return 10000

  • Function parameters are listed inside the parentheses () in the function definition.
  • Function arguments are the values received by the function when it is invoked.

A function can accept multiple parameters:
function getVolume(width, length, height) {