So far, the functions we've created execute a fixed task without context / inputs. But most often we want our functions to produce different outcomes depending on the context behind the function call.
For example, it would be nice if sayHello()
would print a personalized message such as "Hello humans" or "Hello cats" or "Hello dogs", depending on the audience instead of "Hello world" no matter what.
Function parameters:
Function parameters allow functions to accept input(s) and perform a task using the input(s). We use parameters as placeholders for information that will be passed to the function when it is called.
When a function is defined, its parameters are specified between the parentheses that follow the function name.
Here is our function with one parameter, audience
:
function sayHello(audience) {
console.log("Hello " + audience);
}
Calling with arguments:
Then we can call sayHello()
and specify the values in the parentheses that follow the function name. The values that are passed to the function when it is called are called arguments.
// Function declaration:
function sayHello(audience) {
console.log("Hello " + audience);
}
//Function call:
sayHello("humans"); // Output: Hello humans
We have passed one string argument: "humans"
. Inside the function audience
will equal string "humans"
and acts just like a regular variable.
Multiple parameters:
A function can have as many parameters as it needs. Here is a function with two parameters:
Here is a function with two parameters:
function sayHello(name, age) {
console.log(name + ", aged " + age);
}
// Let's call it:
sayHello("John", 30); // Output: John, aged 30
sayHello("Mary", 26); // Output: Mary, aged 26
Notice that the order in which arguments are passed and assigned follows the order that the parameters are declared.
Variables as arguments:
Variables can also be passed as arguments for function calls:
function sayHello(name, age) {
console.log(name + ", aged " + age);
}
let name = "Andy";
let age = 28;
sayHello(name, age); // Output: Andy, aged 28
sayHello("Mary", age); // Output: Mary, aged 28
Assignment
Follow the Coding Tutorial and let's write some functions.
Hint
Look at the examples above if you get stuck.
In this lesson, we will explore the concept of function parameters and arguments in JavaScript. Understanding how to use parameters and arguments is crucial for writing flexible and reusable functions. This knowledge is fundamental for any JavaScript developer, as it allows functions to handle different inputs and produce varied outputs based on those inputs.
Function parameters and arguments are particularly useful in scenarios where you need to perform similar operations on different data sets, such as processing user inputs, handling API responses, or manipulating arrays and objects.
Before diving into more complex examples, let's understand the basic concepts of function parameters and arguments:
Consider the following simple example:
function greet(name) {
console.log("Hello " + name);
}
greet("Alice"); // Output: Hello Alice
greet("Bob"); // Output: Hello Bob
In this example, name
is the parameter, and "Alice" and "Bob" are the arguments passed to the function when it is called.
Let's delve deeper into the key concepts and techniques related to function parameters and arguments:
A function can have a single parameter, as shown in the example above. The parameter acts as a variable within the function, holding the value of the argument passed during the function call.
A function can also have multiple parameters. The order in which arguments are passed during the function call must match the order of the parameters in the function declaration:
function introduce(name, age) {
console.log(name + " is " + age + " years old.");
}
introduce("Alice", 25); // Output: Alice is 25 years old.
introduce("Bob", 30); // Output: Bob is 30 years old.
In this example, name
and age
are parameters, and the function is called with different arguments to produce different outputs.
Let's explore more examples and real-world use cases:
function calculateArea(length, width) {
return length * width;
}
console.log(calculateArea(5, 10)); // Output: 50
console.log(calculateArea(7, 3)); // Output: 21
In this example, the function calculateArea
takes two parameters, length
and width
, and returns the area of the rectangle.
function greetPeople(greeting, name) {
console.log(greeting + ", " + name + "!");
}
greetPeople("Good morning", "Alice"); // Output: Good morning, Alice!
greetPeople("Hello", "Bob"); // Output: Hello, Bob!
In this example, the function greetPeople
takes two parameters, greeting
and name
, and prints a personalized greeting message.
When working with function parameters and arguments, it's important to be aware of common pitfalls and follow best practices:
Example of using default parameters:
function greet(name = "Guest") {
console.log("Hello " + name);
}
greet(); // Output: Hello Guest
greet("Alice"); // Output: Hello Alice
Let's explore some advanced techniques related to function parameters and arguments:
Rest parameters allow a function to accept an indefinite number of arguments as an array:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(4, 5, 6, 7, 8)); // Output: 30
In this example, the sum
function uses the rest parameter ...numbers
to accept any number of arguments and calculates their sum.
Here is a comprehensive example demonstrating the use of function parameters and arguments:
// Function to calculate the area of a rectangle
function calculateArea(length, width) {
return length * width;
}
// Function to greet a person with a personalized message
function greetPerson(greeting, name) {
console.log(greeting + ", " + name + "!");
}
// Function to calculate the sum of multiple numbers
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// Calling the functions with different arguments
console.log(calculateArea(5, 10)); // Output: 50
greetPerson("Good morning", "Alice"); // Output: Good morning, Alice!
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
When debugging and testing functions with parameters and arguments, consider the following tips:
console.log
to print the values of parameters and arguments to verify their correctness.Example of a simple unit test using a testing framework like Jest:
test('calculateArea should return the correct area', () => {
expect(calculateArea(5, 10)).toBe(50);
expect(calculateArea(7, 3)).toBe(21);
});
test('greetPerson should print the correct greeting message', () => {
console.log = jest.fn();
greetPerson("Hello", "Bob");
expect(console.log).toHaveBeenCalledWith("Hello, Bob!");
});
test('sum should return the correct sum of numbers', () => {
expect(sum(1, 2, 3)).toBe(6);
expect(sum(4, 5, 6, 7, 8)).toBe(30);
});
When approaching problems related to function parameters and arguments, consider the following strategies:
In this lesson, we covered the fundamental concepts of function parameters and arguments in JavaScript. We explored how to define functions with parameters, call them with arguments, and handle multiple parameters. We also discussed common pitfalls, best practices, and advanced techniques like rest parameters.
Mastering function parameters and arguments is essential for writing flexible and reusable code. By practicing and experimenting with different examples, you can enhance your understanding and become proficient in using these concepts in your JavaScript programs.
For further reading and practice, consider the following resources: