JS Function Parameters

Overview

Function parameters are placeholders in a function's definition that allow you to pass values into the function when it's called. They enable you to make functions more flexible and versatile by allowing them to work with different input values.


Defining Function Parameters

Function parameters are declared within the parentheses of a function's definition. They act as variables that receive values when the function is invoked.

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

greet("Alice");
        
    

Passing Arguments

Arguments are the actual values passed into a function when it's called. They correspond to the function's parameters based on their position.

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

greet("Alice");   // "Alice" is the argument passed to the 'name' parameter
        
    

Multiple Parameters

Functions can have multiple parameters, allowing you to pass in multiple values.

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

var sum = add(5, 3);   // sum is 8
        
    

Default Parameters (ES6)

ES6 introduced default parameter values that are used if an argument is not provided when the function is called.

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

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

Rest Parameters (ES6)

Rest parameters allow you to pass an arbitrary number of arguments as an array.

Try yourself
        
            function sum(...numbers) {
    return numbers.reduce((acc, num) => acc + num, 0);
}

var total = sum(1, 2, 3, 4);   // total is 10

function printInfo(firstName, lastName, ...otherInfo) {
    console.log(`Name: ${firstName} ${lastName}`);
    console.log(`Other info: ${otherInfo.join(', ')}`);
}

printInfo('John', 'Doe', 'Age: 30', 'Occupation: Developer');

function sum(...numbers) {
    let result = 0;
    for (let num of numbers) {
        result += num;
    }
    return result;
}

console.log(sum(1, 2, 3));       // Output: 6
console.log(sum(1, 2, 3, 4, 5)); // Output: 15

        
    

Arguments Object

The arguments object is an array-like object available within functions that holds all the arguments passed to the function.

Try yourself
        
            function displayArguments() {
    for (var i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }
}

displayArguments(1, "hello", true);
// Outputs: 1
//          hello
//          true

        
    

Summary

Function parameters allow you to pass values into functions, enabling them to work with different inputs and enhancing the flexibility of your code.