Function Parameters and Return Values
Functions become more useful when we can send them information and get something back. In JavaScript, we use parameters to pass data into functions, and we use the return
keyword to send a result back. This makes functions more powerful and flexible, letting us reuse the same logic with different values.
Passing arguments to functions
You can pass values into a function using parameters. These are like placeholders for the values (called arguments) you give when calling the function.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
greet("Bob"); // Output: Hello, Bob!
Here, name
is the parameter, and "Alice"
is the argument passed into the function.
Returning values with return
Functions can also return a value using the return
keyword. This lets you use the result somewhere else in your code.
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result); // Output: 8
Once a function hits a return
statement, it stops running and sends the result back to where it was called.
Default parameters
You can set default values for parameters in case the caller doesn't provide them. This helps prevent errors and gives your function some fallback behavior.
function greet(name = "friend") {
console.log("Hello, " + name + "!");
}
greet(); // Output: Hello, friend!
greet("Sami"); // Output: Hello, Sami!
With default parameters, your functions become more flexible and less likely to break when no arguments are passed.