In this lab, we cover functions and how to modularize our code.
Open functions.js in your text editor and solve the two challenges listed.
The problems are written as code comments //, which means they won't be executed by JavaScript. Make sure to run your code after each attempt to make sure you don't have any bugs!
Declaring a function with no parameters
Declaring functions with parameters
Calling existing functions
Writing if/ else if/ else conditional statements
Using logical expressions and logical operators
Declaring and initializing variables, assigning data to variables
An algorithm is a sequence of one or more instructions toward accomplishing a task. Think of an algorithm like a step-by-step recipe, plan, or procedure.
A function is a reusable algorithm that has been packaged and given a name.
Functions allow us to create concise and reusable code that can be repeated or applied across many contexts. Functions also allow us to organize our code into separate components, making it easier to read, update, and debug large programs.
A function declaration begins with the keyword function, and is followed immediately by the name of the function, a pair of parentheses, and a pair of curly braces.
The name of the function should describe what the function does. Function names should generally begin with a verb and be written in camelcase.
function takeAttendance() {
}
Now that we have defined "takeAttendance" as a function, from here on we will refer to it as takeAttendance(), with parentheses to communicate that it is a function and not a variable.
The next step would be adding the code that the function will execute. Within the curly braces, we will write the code to, in this case, take attendance.
function takeAttendance() {
//Count the number of students present.
}
A few important points:
All code you want to run should be placed inside the curly braces.
To keep things neat, all code immediately within the curly braces should be indented using the TAB key on your keyboard.
To use the function that exists, the function has to be callled.
Calling a function means executing the code within the specified function. To call a function, specify the function name including the parentheses at the end.
For example, to call our function, simply write takeAttendance(); When the computer processes that statement, it attempts to run the code found inside takeAttendance()'s curly braces.
We can call a declared function anywhere in our script, above or below the function declaration itself. In the example below, the function is called below the declaration.
function takeAttendance() {
//Count the number of students present.
}
takeAttendance();
Functions can be called limitlessly. Functions are meant to be reusuable so anytime you find yourself writing a piece of code repetitively, try writing a function for it!
If you need an example, look at our function example. Think about how many times your coach will have to take attendance throughout the course of this program. The coach will probably use that function multiple times.
Functions should be reusable. Part of being reusable is being versatile, meaning the function can adapt to situations based on certain variables.
A parameter is a placeholder variable that a function expects to be passed a value when the function is called. Parameters should be placed within the parentheses of the function declaration, which we call the parameter list. If a function has more than one parameter, each additional parameter in the list must be comma-separated.
For example, this function has two parameters: num1 and num2
function subtract(num1, num2) {
console.log(num1 - num2);
}
If we want to call subtract(), we need to pass two arguments, or values, into the function, one for each parameter.
Values passed into a function are called arguments, and represent input.
Arguments must be passed in the same order that the parameters appear in the function declaration. For example:
function subtract(num1, num2) {
console.log(num1 - num2);
}
subtract(6, 2); // This will return 4.
subtract(2, 6); // This will return -4.
When we declare a function with parameters and then call that function, the function expects an argument for each parameter.
If you called the function: subtract(6);
You should get this result: NaN
The value NaN means "not a number". We got NaN because we tried subtracting a missing second argument from 6. In JavaScript, missing arguments are set to undefined. In other words, since Node doesn't know how to evaluate 6 - undefined, it gives us NaN as a result.
JavaScript has a few ways of dealing with missing arguments. The most up-to-date way is to create a default value for a parameter.
A default parameter is a parameter that is given a default value if a function is called with missing or undefined arguments.
To set a parameter's default value, assign it that value in the parameter list, like so:
function subtract(num1 = 0, num2 = 0) {
console.log(num1 - num2);
}
Now, if you call:
subtract(6); // This will return 6.
The function replaced num2 with 0 instead of undefined.
If you called the function with no arguments:
subtract(); // This will return 0.
For now, you can just assume JavaScript ignores all extra arguments.
If you called:
subtract(6, 2, 5); // This will return 4.
Just as functions have input in the form of arguments, they have output. So far we have been using console.log() to simulate output, but this is not truly making functions "produce" anything. Remember, console.log() merely prints things to the terminal. In order for a function to actually produce output, we need to use a return statement.
A return statement causes a function to immediately produce a value on the spot. This will also cause the execution of any other code in that function to be terminated.
Let's edit the subtract() function so that it returns a value.
function subtract(num1 = 0, num2 = 0) {
return num1 - num2;
}
subtract(6, 2);
If you run this, you'll notice... absolutely nothing! However, if we make a few changes...
function subtract(num1 = 0, num2 = 0) {
return num1 - num2;
}
let diff = subtract(6, 2);
console.log(diff);
Now you should see the difference printed to the terminal.
Here's the key point. The subtract() function is returning a value, not printing a value. That's a very important distinction.
Returning is like passing a football. The quarterback is the function, and the football is the output. If not one is there to catch the football, what happens? Nothing! In this case, the variable diff caught the football, which is the value 4. This allowed us to then print 4 to the terminal.
A return statement causes a function to immediately exit.
function subtract(num1 = 0, num2 = 0) {
return num1 - num2;
console.log("You can't see this!");
}
Here, notice that the "You can't see this!" message will never execute. That statement is considered "unreachable".
Depending on the circumstances, you won't always require a "catcher" variable. For example, you can pass one function's output to another function as input.
For example, let's pass the output of subtract(6, 2) to console.log() as input:
function subtract(num1 = 0, num2 = 0) {
return num1 - num2;
}
console.log(subtract(6, 2));
Here, console.log() acts as the "catcher". Because subtract(6, 2) returns 4, console.log() receives it as input, and then prints it.
Try to figure out what values are printed with these two lines:
console.log(subtract(100, 50) + subtract(100, 50));
console.log(subtract(subtract(6, 2), 4);
Let's now augment our subtract() function to return the absolute difference between two numbers. For example, both subtract(6, 2) and subtract(2, 6) should return 4. To do this, we have to find the larger of the two arguments.
function calcAbsoluteDiff(num1 = 0, num2 = 0) {
if (num1 > num2) {
return num1 - num2;
}
return num2 - num1;
}
Notable Changes
The name of the function is changed to reflect the purpose of the function.
Use conditionals within the function to identify the larger number and execute the corresponding code.
Because return statement immediately causes a function to stop, the else conditional is optional
If you call a function that doesn't have a return statement, that function will simply return an undefined value by default. In other words, just as the default value of every JavaScript variable is undefined, the default return value of every JavaScript function is also undefined.
You have already seen an example of this when calling console.log() from within the Node REPL. Notice that when you call this function you also see undefined printed out; that's because, for convenience, the REPL always prints what expressions and functions return or evaluate to.
YouTube (whatsdev) JavaScript Functions. (Mentions material that you haven't covered yet, but still useful)