2.4 - Function Parameters

How long does it take to get from Louisiana to Alabama?

One Mississippi.

Review

  • Code is run line-by-line in a code file - unless we "chunk" it into mini-programs called functions.

  • Functions are run by "calling" them. For example: areaOfTriangle() or console.log()


2.4 - Function Parameters

Ever notice that we can 'pass' or 'give' values to Math.round(), console.log(), and prompt() by putting something inside the brackets? Example: Math.round(3.14) or prompt("Please enter a number")

When we put something inside the brackets, that is called an argument. It gives the function some data to process. When you write your own functions, you can declare parameters that need to be filled.

Example: The third angle in a triangle

function thirdAngle(a, b) {

// The parameters a, and b will be automatically declared
// and will have whatever values are passed as arguments

console.log(180 - a - b);

}

Perhaps we then want to call thirdAngle() several times with different values for a, and b:

thirdAngle(25, 113);
thirdAngle(90, 40);
thirdAngle(63, 71);

This means we don't necessarily need to ask the user for input.


Functions can call other functions and pass parameters around!

function level1(x) {
// Pass on the parameter!
level2(x);
}

function level2(y) {
// Pass on the parameter plus 1!
level3(y + 1);
}

function level3(z) {
// Print it
console.log("Level 3 says", z);
}

// Call level1 to test it. Should print 5
level1(4);



You can have as many parameters as you want but:

  • The order you define the parameters matters!

    • Arguments need to match the parameter order

For Example, this definition of a function specifies parameters:

function lotsOfWork(name, phoneNumber, age, grade, height) {

}

When we call that function, we need to include all of those values and in that same order as arguments!

lotsOfWork("Mr. Squirrel", "555-555-5555", 10, 12, 18)

Task 2.4

Let's practice making functions with parameters in the Replit project for 2.4.