Introduction to Functions

Functions take inputs, perform computations, and then return an output. Here is an example of a function that takes two numbers as inputs, adds the numbers, and then returns the sum:

function add(x, y) {
  return(x + y);
}

After a function is defined, it can be invoked to execute the code and get a return value.

console.log(add(3, 4)); // 7

Below is an example of a function that takes a firstName and lastName as inputs, concatenates the strings into a single string, and returns the full name as output:

function fullName(firstName, lastName) {
  return(firstName + ' ' + lastName);
}

Here is how the function can be invoked with the "Matt" and "Powers" arguments:

fullName("Matt", "Powers"); // "Matt Powers"

The following example has comments to explain all the new function jargon.

function silly(x) {
  return(x + 'is silly!');
} // function named silly is defined
silly("dave"); // the silly function is invoked with the argument "dave"

To summarize:

- functions can take zero, one, or more input values
- functions perform computations
- functions return a single value
Question Click to View Answer

What does the following code print to the console?

function subtract(x, y) {
  return(x - y);
}
var r = subtract(100, 4);
console.log(r);

96

The subtract function is defined and programmed to take two arguments. The subtract function is then invoked with the arguments 100 and 4, and the resulting output is assigned to the variable r. r is printed to the console.

What does the following code print to the console?

function inchesToCentimeters(n) {
  return(n * 2.54);
}
var r = inchesToCentimeters(10);
console.log(r);

25.4

The inchesToCentimeters function converts inches to centimeters. 10 inches is equivalent to 25.4 centimeters.

What does the following code print to the console?

function stringLength(s) {
  return(s.length);
}
var r = stringLength("cool");
console.log(r);

4

The stringLength() function returns the number of characters in a string. In this example, the stringLength() function is invoked with the argument "cool" and returns the integer 4.

<-- Previous (More Arrays) Next (Variable Scope) -->