2.4 - Function Parameters

Review

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

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


Today's Lesson: 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?

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 Quadratic Formula

function quadFormula(a, b, c) {

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

}

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

quadFormula(2, 3, -4);
quadFormula(
1, 8, 19);
quadFormula(
3, 3, 3);

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(x) {
// Pass on the parameter plus 1!
level3(x + 1);
}

function level3(x) {
// Print it
console.log(x);
}

// Call level 1 to test it
level1(4); // This will print 5

Notice that we used 'x' as the variable several times? This is not necessary but each function has its own version of the variable - so they aren't the same.


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:

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!

Task 2.4

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