Instagram
youtube
Facebook
Twitter

Parameters and Return Values

In this lesson, we will cover how to pass values into functions using parameters and how to return values from functions. Parameters and return values make functions more flexible and reusable, allowing you to perform operations with different inputs and retrieve useful results.


1. Introduction to Parameters and Arguments

Parameters are variables defined in the function’s declaration that act as placeholders for the values the function will use. When calling a function, these values are known as arguments.

Example:

function greet(name) { // 'name' is a parameter
    console.log("Hello, " + name + "!");
}

greet("Alice"); // "Alice" is the argument passed to the function

In this example, name is the parameter, while "Alice" is the argument that gets passed to the greet function when it is called.


2. Multiple Parameters

Functions can take multiple parameters, separated by commas. When calling the function, you provide the corresponding arguments in the same order as the parameters.

Example:

function add(a, b) {
    return a + b;
}

console.log(add(3, 5)); // Outputs: 8

In the add function, a and b are parameters, while 3 and 5 are arguments passed to the function. The function returns the sum of a and b.


3. Default Parameters

JavaScript allows you to set default values for parameters. If an argument is not provided when the function is called, the parameter will take on its default value.

Syntax:

function functionName(parameter = defaultValue) {
    // Code to execute
}

Example of Default Parameters:

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

greet("Alice"); // Outputs: Hello, Alice!
greet();        // Outputs: Hello, stranger!

In this example, if name is not provided, it defaults to "stranger".


4. The return Statement

The return statement allows a function to output a value back to the caller. When a return statement is reached, the function stops executing and returns the specified value.

Example:

function multiply(a, b) {
    return a * b;
}

let result = multiply(4, 5); // Returns 20
console.log(result);          // Outputs: 20

In this example, the multiply function returns the product of a and b. The result is stored in result and then printed.


5. Returning Without a Value

If a function doesn’t include a return statement, it will return undefined by default.

Example:

function sayHello() {
    console.log("Hello!");
}

let output = sayHello(); // Outputs: Hello!
console.log(output);      // Outputs: undefined

In this example, sayHello() prints "Hello!" but doesn’t return anything, so output is undefined.


6. Returning Complex Data Types

Functions can return complex data types, such as objects or arrays, making them useful for handling and organizing multiple values.

Example:

function getUserInfo(name, age) {
    return {
        name: name,
        age: age,
        isAdult: age >= 18
    };
}

const userInfo = getUserInfo("Alice", 25);
console.log(userInfo);
// Outputs: { name: "Alice", age: 25, isAdult: true }

In this example, getUserInfo returns an object with details about the user, including whether they are an adult. Returning complex data structures helps keep code organized and accessible.


7. Arrow Functions with Parameters and Return Values

Arrow functions handle parameters and return values similarly to traditional functions. For single expressions, they support an implicit return, meaning you can skip the return keyword and braces {}.

Example:

const square = x => x * x;
console.log(square(4)); // Outputs: 16

With multiple parameters and complex function bodies, arrow functions require parentheses and braces.

Example with Multiple Parameters:

const add = (a, b) => {
    return a + b;
};
console.log(add(3, 5)); // Outputs: 8

8. Practical Uses of Parameters and Return Values

Parameters and return values allow functions to work in flexible, dynamic ways:

  • Modularity: Instead of hardcoding values, functions can receive data from arguments, making code more adaptable.
  • Reusable Components: Functions can handle various tasks based on provided inputs.
  • Encapsulation: Functions can process data internally and return a result, hiding complexity from the user.

Example of a Modular Function:

function calculateDiscount(price, discountRate) {
    return price * (1 - discountRate);
}

let discountedPrice = calculateDiscount(100, 0.2); // 20% discount
console.log(discountedPrice); // Outputs: 80

This function can apply any discount rate to any price, making it reusable across different scenarios.


9. Coding Exercises

Create a JavaScript file named parametersAndReturnValuesPractice.js and complete the following exercises:

  1. Multiplication Table: Write a function generateTable that takes a number as input and returns an array with its multiplication table up to 10.

    console.log(generateTable(5)); // Outputs: [5, 10, 15, ..., 50]
    
  2. Grade Calculator: Create a function calculateGrade that takes a score (0–100) and returns a grade as follows:

    • A for 90–100
    • B for 80–89
    • C for 70–79
    • D for 60–69
    • F for 0–59
  3. Sum of Array: Write an arrow function sumArray that takes an array of numbers and returns the sum of all the elements.

    console.log(sumArray([1, 2, 3, 4])); // Outputs: 10
    

Example Solutions:

// 1. Multiplication Table
function generateTable(num) {
    let table = [];
    for (let i = 1; i <= 10; i++) {
        table.push(num * i);
    }
    return table;
}

// 2. Grade Calculator
function calculateGrade(score) {
    if (score >= 90) return 'A';
    else if (score >= 80) return 'B';
    else if (score >= 70) return 'C';
    else if (score >= 60) return 'D';
    else return 'F';
}

// 3. Sum of Array
const sumArray = arr => arr.reduce((sum, num) => sum + num, 0);

Conclusion

In this lesson, you learned about parameters, arguments, and return values. These concepts allow you to create more flexible and reusable functions by handling various inputs and returning outputs. Understanding how to work with parameters and return values is essential for writing effective functions in JavaScript.

In the next lesson, we’ll explore Scope and Hoisting, where you’ll learn how variables behave within functions and the broader JavaScript environment.