Parameters and Return Values in JavaScript

 

Functions are awesome, but they become even more powerful when they accept input (parameters) and return output (return values). Think of them as vending machines—you put something in (money), and you get something out (snacks). 

1. What are Parameters?

Parameters are placeholders that allow a function to accept input. They make functions flexible and reusable, just like a Swiss Army knife. 

Example:

function greet(name) {
  console.log("Hello, " + name + "!");
}
greet("Alice");
greet("Bob");

Output:

Hello, Alice! 
Hello, Bob! 

Real-life analogy: Ordering coffee with your name on it.

2. Multiple Parameters 

Functions can have multiple parameters, just like a food delivery order with multiple items. 

Example:

function add(a, b) {
  console.log("The sum is: " + (a + b));
}
add(5, 3);
add(10, 20);

Output:

The sum is: 8
The sum is: 30

Real-life analogy: Splitting a restaurant bill with friends.

3. Return Values

A return value is what a function sends back as a result. Without return, a function just performs an action but doesn't give anything back.

Example:

function multiply(x, y) {
  return x * y;
}
let result = multiply(4, 5);
console.log("The result is: " + result);

Output:

The result is: 20

Real-life analogy: Asking a friend for a pen and actually receiving one.

4. Return vs. Console.log 

Feature return console.log
Purpose Sends a value back Just prints to console
Can be used later? Yes No
Common analogy Getting change from a cashier Making an announcement with a megaphone 

Example:

function getDiscount(price) {
  return price * 0.1; // Returns 10% discount
}
let discount = getDiscount(100);
console.log("Discount is: $" + discount);

5. Default Parameters

JavaScript allows default values for parameters in case no arguments are provided.

Example:

function greet(name = "Stranger") {
  console.log("Hello, " + name + "!");
}
greet(); // Uses default

Output:

Hello, Stranger!

Real-life analogy: Getting a mystery-flavor candy when you don’t pick one.

Conclusion

Parameters and return values make functions incredibly powerful. They allow you to customize behavior and get results like a pro.

Post a Comment

0 Comments