functions

In this module we'll study functions.

File Location

Use the following file:

            └── 3-JavaScript-Basics
                06-functions.js       <----You will be working here.

Description

Functions allow us to execute some action or actions. They are the lifeblood of your program, and they are used everywhere! Go to any site, and functions are firing. Again, functions allow us to execute some action, and they are able to be used in a repeated fashion.

Declaration

Here's an example of a declaration of a function:

//1        //2
function hello() {
    //3
    console.log("Hello World!");
}
  1. We use the function keyword to notify that this is a function.

  2. We name the function hello. We can name it whatever we want, as long as it's not a keyword. We'll talk about the parenthesis more soon.

  3. We execute some code when the function is called.

Calls

When we want to call a function, that means that we're going to use it, we say the name of the function followed by parenthesis:

hello();

We can call the function any number of times:

hello();
hello();
hello();

Practice

Write a function that prints "Pacers won!" to the console.

function pacersWon(){
    console.log("Pacers won!");
}
pacersWon();

What happens if we call the function 5 times?

pacersWon();
pacersWon();
pacersWon();
pacersWon();
pacersWon();

Parameters and Arguments

A few things to know up front:

  • Parameters are the names listed in the function definition.

  • Arguments are the real values received by the function when you call it.

Here's a function with a parameter:

function numberEntered(x){
    console.log("The number you entered was: ", x);
}

Think of the x parameter just like a variable that can take in a different value each time that the function is called. When we call the function it must now have an argument to satisfy the parameter:

numberEntered(5);
numberEntered(4);
numberEntered(3);
numberEntered(2);
numberEntered(1);

Two Params

Let's try this same thing with two params(slang for parameters, of course)

function addAnyTwoNumbers(x, y){
    console.log(x + y);
}

addAnyTwoNumbers(4, 5);
addAnyTwoNumbers(6, 11);
addAnyTwoNumbers(7, 8);

Get Some Reps

Do that same thing again without looking up at the code above:

  • Write a function that subtracts two numbers.

  • Call the function subtractTwoNumbers.

  • It should have two parameters: firstNum and secondNum.

  • Print the difference of when the firstNum is subtracted from the secondNum to the console.

  • Call the function once, with arguments of 5 and 7.

The Answer

//Declare it
function subtractTwoNumbers(firstNum, secondNum){
    console.log(secondNum - firstNum);
}

//Call it
subtractTwoNumbers(5, 7);

The return Keyword

When JS reaches a return statement it will stop executing that function. The return is the value that the function spits out. It is the value that gets distilled down and returned out of the function. It's best to see it with a function that does some math:

Declare the function:

function getMyTaxReturnAndDoMyTaxesAndStuff(a, x, y, z){
    let myInc = a * x;
    let myTaxes = myInc - y;
    let total = myTaxes + z;
    return total; 
}

Call the function with arguments

getMyTaxReturnAndDoMyTaxesAndStuff(10000, 5, 50000, 0);

Reading Exercise: Do some reading of the code above. Take a few minutes to let the concept properly click. See how the let variables are working together with the paramters. See how data is being passed around.

Answer this job interview type question:

  • Explain how the return keyword works in a function.

Possible Answer

  • We create a function with parameters a, x, y, z.

  • We called the function and pass in argument values to fulfill the parameter.

  • Inside the function, we do some math and distill the value down in our total variable.

  • We return the total outside of the function.

More practice

Write a function that returns the value of two numbers added together.

Write a function that takes in a first and last name. It returns a whole name.

Write a function that returns your pet's name and breed.

Possible Solutions

Write a function that returns the value of two numbers added together.

function add(x, y){
    let sum = x + y;
    console.log(sum);
    return sum;
}

add(1, 1);

Write a function that takes in a first and last name. It returns a whole name.

function fullName(first, last){
    var wholeName = first + " " + last;
    console.log(wholeName);
    return wholeName;
}

fullName("Paul", "O'Connor");

Write a function that returns your pet's name and breed.

function petNameAndBreed(name, breed){
    var petDetails = name + ", " + breed;
    console.log(petDetails);
    return petDetails;
}
petNameAndBreed("Sansa", "Generic");

Great Challenge

Write a function that calculates the the totalPrice after tax on any quantity of any price on a product.

Careful. A possible answer is below.

Answer

function calculatePriceIndiana(quantity, price){
    var tax = 0.07;
    var totalTax = quantity * price * tax;
    var totalPrice = totalTax + quantity * price;
    console.log(totalPrice);
    return totalPrice;
}

calculatePriceIndiana(17, 5);

We'll get plenty more practice in later with functions. Just do your best to understand them for now.

Last updated