Introduction to Computer Algorithm: Data Structures, Complexity, and Optimization for Modern AI Systems

Making Functions Work for You: Parameters and Return Values

Section 3

Organizing Your Thoughts: Functions and Modularity

Introduction to Computer Algorithm: Data Structures, Complexity, and Optimization for Modern AI SystemsOrganizing Your Thoughts: Functions and Modularity

So far, we've learned that functions are like mini-programs that perform specific tasks. But how do we give these functions the information they need to do their job, and how do they communicate the results back to us? This is where parameters and return values come in. Think of parameters as the ingredients you hand to your chef (the function), and the return value as the delicious dish they present back to you.

Parameters: The Inputs to Your Functions

Parameters are variables that are declared within the parentheses of a function's definition. They act as placeholders for the data that the function expects to receive when it's called. When you call a function, you provide actual values, called arguments, which are then assigned to these parameters.

function greet(name) {
  console.log('Hello, ' + name + '!');
}

In the example above, name is a parameter. When we call greet('Alice'), the string 'Alice' becomes the argument for the name parameter. The function then uses this value inside its body.

greet('Alice'); // Output: Hello, Alice!
greet('Bob');   // Output: Hello, Bob!

Functions can have multiple parameters, separated by commas. This allows them to receive more complex information.

function add(num1, num2) {
  let sum = num1 + num2;
  console.log(sum);
}
add(5, 3); // Output: 8
add(10, 20); // Output: 30
チャプターへ戻る