Functions

This lesson is part of the Web Programming 1 Course.

Programs that we write as developers often repeat some task over and over again. Let's assume, for some weird reason, we need to execute the following 3 lines of code multiple times in our program:

console.log("---------------");
console.log(" Hello World! ");
console.log("---------------");

One way to do this would be to copy and paste these statements throughout our program each time we wanted execute them. But there is a much better approach. We can put the statements inside a function, and then we wouldn't need to duplicate them each time we we want them execute.

Functions are a fundamental programming concept that are used all languages. They generally work the same, regardless of the language, but the syntax will vary from one language to another.

Here's how we can use a function to execute the 3 console log statements:

// First declare the function:
function sayHello(){
	console.log("---------------");
	console.log(" Hello World! ");
	console.log("---------------");
}

// Then use function 2 times:
sayHello();
sayHello();

When you run this code in the browser, and look in the console log, you'll see that it says 'Hello World!' (with the dashes) two times.

Functions allow you to execute a group of statements multiple times in your program without having to repeat code.

There are two steps to incorporating functions into your programs:

  1. Declare the function - this is where you define the function by giving it a name and putting the statements inside of it (more details on this in a minute).
  2. Use the function whenever you want the statements in it to execute. 'Use' is not the correct technical term, instead programmers will often say call the function, or invoke the function.

After you declare a function you may call/invoke the function as many times as you like. In order to call/invoke a function in your code, you type the function name followed by a pair of parenthesis. Calling/invoking a function is considered a statement, so you should end the line with a semi-colon, but in JavaScript the semi-colon is often optional.

The Syntax for Declaring a Function

Now let's get into the details and the syntax of declaring a function. Here's a basic template for the syntax you must use to declare a function:

function nameGoesHere(parameters go here){
	statements go here (make sure they are indented)
}

To declare a function:

  1. First type function. This is another keyword in JavaScript (like const and let) and it's required in order to declare a function.
  2. Next, after a space, type the name of the function. You should come up with a name that helps to describe what the function does. And, in JavaScript, you should use camelCase when naming your functions (there are other rules to naming your functions too, they are similar to the rules for naming variables).
  3. After the name you must type a pair of parenthesis, and inside the parenthesis you can add 'parameters', which are optional and we'll talk more about them very soon.
  4. After the parenthesis, you put a pair of curly braces: { and }
  5. Inside the curly braces you put the statements that are to be executed whenever the function is called/invoked. It's very important for you to indent the statements that you put inside a function. The code in between the curly braces is known as the body of the function.

There are a few different ways to declare a function, which will affect how you use (invoke/call) it, and how it will behave.

Parameters

The sayHello function that we declared above did not include any parameters. Parameters allow you to feed information into your functions, which can make them extremely flexible and powerful. As a simple example, assume that you want to write a function that applies sales tax to the price of a product. You want this function to be able to figure out the total (after taxes) for any product price. In order to make the function flexible enough to work with any price, you could declare it like so:

function calculateTotalPrice(preTaxPrice){
	const salesTaxRate = 0.07; // assume 7% sales tax
	const totalPrice = preTaxPrice * (1 + salesTaxRate);
	alert("Total Price: " + totalPrice) 
}

Note the following about this function:

  1. The name of the function is calculateTotalPrice
  2. The function defines a parameter named preTaxPrice which is in between the parenthesis.
  3. The code in the body of the function will use the parameter to calculate the total cost of the product, and then it will display the total in an alert.

The beauty of this function is that it can calculate the total price for any product. This is how we might make use of the function by calling/invoking it:

// Example 1 - calculate the total for a product that costs $100.00
calculateTotalPrice(100.00); 

// Example 2 - allow the user to enter any price
const price = prompt("Enter the price of a product");
calculateTotalPrice(price);

Notice that when you call/invoke the function you can specify a value in between the parenthesis. This value will be assigned to the preTaxPrice parameter when the code in the body of the function executes.

In the first example, we are 'passing in' a value of 100.00 as the parameter (programmers describe invoking a function with parameter by saying something like 'call the function and 'pass in' a value of...).

In the second example, we are allowing the user to 'pass in' any value they want, which makes our function flexible enough to handle any product price. We do this by prompting the user for input and storing the input in the price variable. Then we 'pass in' the price when we invoke the calculateTotalPrice function.

You can come up with your own parameter names when you declare functions (although some rules apply, just as there are rules to naming variables), but you should follow these guidelines:

Return Values

So far, none of the functions we created returned a value, which is another feature that you can add when declaring a function. Let's create a function that has a parameter and returns a value. But first consider this code, which converts various numbers from celsius to fahrenheit:

const f1 = 10 * 9/5 + 32; //convert 10 degrees celsius to fahrenheit
const f2 = 50 * 9/5 + 32; //convert 50 degrees celsius to fahrenheit
const f3 = 75 * 9/5 + 32; //convert 75 degrees celsius to fahrenheit
const f4 = 100 * 9/5 + 32; //convert 100 degrees celsius to fahrenheit

Notice that we are duplicating the equation to convert celsius to fahrenheit multiple times (programmers always try to avoid code duplication). Instead we can declare a function that allows you to convert any number from celsius to fahrenheit. We'll use a parameter to act as a placeholder for that number. Here's what the function might look like:

function convertToFahrenheit(tempCelsius){
  const tempFahrenheit = tempCelsius * 9/5 + 32;
  return tempFahrenheit;
}

Here are some notes about the function:

  1. The name of the function is convertToFahrenheit (in camelCase), which is a good name because it describes what the function does.
  2. The function defines a parameter, which is named tempCelsius. This parameter acts as a placeholder for the number that will be converted from celsius to fahrenheit. You can think of a parameter as a variable that can be used in the body of the function (remember, the body of a function is the group of statements that are in between the curly braces). You'll see how to specify exactly what number to convert in a minute, when we call/invoke the function.
  3. The first statement inside the body declares a variable named tempFahrenheit and initializes it by using the parameter (tempCelsius) in an expression.
  4. The second statement in the body 'returns' the temperature in fahrenheit. return is another keyword in JavaScript, and it means that you can use the function in order to initialize a variable, as we'll see in the next code sample.

Now that we have declared a function that will convert any number from celsius to fahrenheit, we can call/invoke it a few times like so:

// convert 10, 50, and 75 to fahrenheit and store the result in f1,f2,f3
const f1 = convertToFahrenheit(10);
const f2 = convertToFahrenheit(50);
const f3 = convertToFahrenheit(75);

// output the fahrenheit temperatures to the console log 
console.log(f1);
console.log(f2);
console.log(f3);

There are two important things to note about these statements:

  1. The number that you want to convert is specified inside the parenthesis. This number will be referred to as tempCelsius inside the body of the function because that's the name we used for the parameter when we declared the function.
  2. Because we included a return statement in the body of the function, we can use the function to initialize a variable. We initialized the f1, f2, and f3 variables to store the temperatures that have been converted to fahrenheit, which is the value that our function returns.

When you call a function and specify a parameter, it's known as 'passing in' a value. So, in the above code sample, we could say that in the first statement we are 'passing in' a value of 10 when calling the convertToFahrenheit function. The

Let's now make our program flexible enough to allow the user to input any number they would like to convert from celsius to fahrenheit:

const celsiusToday = prompt("What's the temp today (in celsius)?");
const fahrenheitToday = convertToFahrenheit(celsiusToday);
alert("Today's temp in fahrenheit is: " + fahrenheitToday);

JavaScript has Built-in Functions

At this point, I should probably point out that prompt and alert are functions! I was referring to them as 'commands' in previous lessons because we had not yet talked about functions. There are many great functions that are built into the JavaScript language that allow you to do all sorts of things, and we'll be exploring more of them as we continue through the course. The best thing about these function is that you don't have to declare them, you can just call/invoke them when you need to.

Another built-in function that we'll use occasionally is parseInt which is used to convert the data type of a value to a number. Here's an example:

let age = prompt("Enter your age in years");
console.log(typeof age); // notice that the data type is string

age = parseInt(age); // parseInt() will return a number
console.log(typeof age); // now the data type is number

In JavaScript, any time a user enters input, the data type will default to string. If you ask the user to enter a number, then you should use the parseInt function to convert the data type to number (we've seen what can happen if you use strings in math equations!).

Variations of Functions

As you have seen, there are various ways to go about declaring a function. Some functions return a value (which means that there is a 'return' statement in the body of the function). Some functions have a parameter, and others don't (the sayHello function did not include a parameter while the convertToFahrenheit function did).

You can also declare a function that has more than one parameter. Here's a function that's useless, except that it demonstrates how to declare a function that has more than one parameter:

function someUselessFunction(param1, param2){
  console.log("The value of the first param is: " + param1);
  console.log("The value of the second param is: " + param2);
}

Note that you must separate the parameter names with a comma. You may also put a space after the comma, which is optional. I like to include the space to make my code more readable by giving it some breathing room.

To call this function, you can add this code:

someUselessFunction("sugar", "spice");

In this code, we are passing in two string values for the parameters. Note that you need to separate the value with a comma (the space is optional).

Let's call the function again, this time we'll pass in different values:

someUselessFunction("salt", "pepper");

In this activity we have seen functions that:

Technically, functions cannot return more than one value. But there are some ways to get around this rule, although we don't need to worry about them at this point.

So there are various ways to design (declare) your functions, and this gives you quite a bit of creative freedom to decide what they can do and how they can be used (how they can be 'called' or 'invoked').

I have noticed that beginning students are often confused by the difference in function that return values and ones that don't. So I have a little quiz for you about this code sample:

const name = prompt("Enter your name");
alert("Hello " + name + "!");

In this code, two functions are being called (invoked). Can you tell which one returns a value? How can you tell?

Modern Syntax for Declaring Functions (Arrow Functions)

There is an alternate syntax that you can use to declare functions in JavaScript that is relatively new. Functions declared in this way are known as arrow functions. We will not be using arrow functions in this class, but we'll explore them more in the next web programming course. But if your curious, here's an example that shows how our convertToFahrenheit() function would look if we had used the arrow function syntax:

const  convertToFahrenheit = (tempCelsius) => {
  const tempFahrenheit = tempCelsius * 9/5 + 32;
  return tempFahrenheit;
}