JavaScript Function Parameters

JavaScript Function Parameters

In JavaScript, function parameters are named variables that allow functions to accept input values. These parameters act as placeholders for data that is provided when the function is executed, enabling the function to perform dynamic operations.

Function parameters make JavaScript code more reusable, flexible, and easier to maintain. Instead of hardcoding values, parameters allow the same function to work with different inputs.

In JavaScript, function arguments are passed using the following concepts:

  • Passed by value: Primitive data types such as numbers, strings, and booleans are passed as copies. Changes made inside the function do not affect the original value outside the function.
  • Passed by reference: Objects and arrays are passed as references. This means modifications inside the function can directly affect the original data.

Function parameters are defined inside the parentheses of a function declaration or expression and are matched with arguments in the same order during function calls.

Syntax

function functionName(parameter1, parameter2, parameter3) {
    // function logic goes here
}
                

Rules of Function Parameters

  • JavaScript does not require explicit data types for function parameters.
  • Parameter data types are determined dynamically at runtime.
  • JavaScript does not perform compile-time type checking on function arguments.
  • If fewer arguments are passed than parameters, the remaining parameters receive the value undefined.

Example: Using Function Parameters

JavaScript Example

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

greet("Alice"); // argument
greet("Bob");   // argument
                    
Try it Yourself »

Default Parameter

Default parameters in JavaScript allow you to define fallback values for function parameters. If a function is called without an argument—or if the argument is explicitly undefined—the default value is automatically used.

This feature, introduced in ES6, helps prevent common runtime errors, improves code readability, and eliminates the need for manual parameter checks inside functions.

Default values are assigned using the equals sign (=) directly in the function definition.

Example 1: Using Default Parameters in a Function

JavaScript Example

function greet(name = "Guest", country = "Unknown") {
  return `Hello ${name}! Country: ${country}`;
}

greet();                          // Hello Guest! Country: Unknown
greet("John");                    // Hello John! Country: Unknown
greet("Emma", "Canada");          // Hello Emma! Country: Canada
            
Try it Yourself »

In this example, the function still works correctly even when arguments are missing. This makes your code safer and more predictable in real-world applications.

Rest Parameters

Rest parameters allow a function to accept an unlimited number of arguments as a single array. This feature is also part of ES6 and uses the spread operator (...).

Rest parameters are ideal when you don’t know in advance how many values will be passed to a function—such as handling user input, calculations, or dynamic data sets.

A function can have only one rest parameter, and it must be the last parameter in the function definition.

Example 2: Using Rest Parameters to Handle Multiple Values

JavaScript Example

function calculateAverage(...scores) {
  let total = 0;

  for (let score of scores) {
    total += score;
  }

  return total / scores.length;
}

console.log(calculateAverage(80, 90));          // 85
console.log(calculateAverage(70, 85, 95));      // 83.33
console.log(calculateAverage(60, 75, 80, 90));  // 76.25
            
Try it Yourself »

Here, the rest parameter collects all provided arguments into the scores array, allowing the function to work with any number of inputs without modification.

Argument Object

In JavaScript, every regular function has access to a built-in object called the arguments object. It stores all values passed to the function at runtime, regardless of how many parameters are declared.

This makes the arguments object useful when working with functions that need to handle a dynamic or unknown number of inputs.

Although arguments looks like an array and supports indexed access, it is not a real array. However, you can still access individual values using indexes and check the total count using arguments.length.

Example: Using the Arguments Object in JavaScript

JavaScript Example

function displayArguments() {
  console.log("Total arguments:", arguments.length);

  for (let i = 0; i < arguments.length; i++) {
    console.log("Argument " + i + ":", arguments[i]);
  }
}

displayArguments("JavaScript Tutorial", 2025, true);
displayArguments("Single value");
displayArguments();
            
Try it Yourself »

The function works correctly no matter how many arguments are passed. This behavior demonstrates how JavaScript dynamically handles function inputs at runtime.

Important: The arguments object is not available in arrow functions. In modern JavaScript, the rest parameter (...args) is generally recommended as a cleaner and more readable alternative.

Passing Argument By Value

In JavaScript, passing an argument by value means that a copy of the original value is provided to the function. Any modification made inside the function affects only the local copy and does not change the original variable.

This behavior ensures data safety by preventing unintended side effects when working with simple values.

All primitive data types—including number, string, boolean, undefined, null, symbol, and bigint— are always passed by value in JavaScript.

Example: Passing a Primitive Value to a Function

JavaScript Example

function applyDiscount(price) {
  console.log("Inside function, original price:", price);
  price = price - 50;
  console.log("Inside function, discounted price:", price);
}

let productPrice = 200;

console.log("Before function call:", productPrice);
applyDiscount(productPrice);
console.log("After function call:", productPrice);
            
Try it Yourself »

Even though the value is modified inside the function, the original variable remains unchanged. This demonstrates how primitive values are passed by value in JavaScript.

Passing Argument By reference

In JavaScript, when non-primitive values such as objects, arrays, or functions are passed to a function, the function receives a reference to the original value rather than a separate copy.

Because both the original variable and the function parameter point to the same memory location, any modification made inside the function directly affects the original object.

This behavior is commonly described as passing by reference, although JavaScript technically passes object references by value.

Example: Modifying an Object Passed to a Function

JavaScript Example

function addItemToCart(cart) {
  cart.items.push("Laptop");
  cart.totalItems = cart.items.length;

  console.log("Inside function:", JSON.stringify(cart));
}

let shoppingCart = {
  items: ["Phone", "Headphones"],
  totalItems: 2
};

console.log("Before function call:", JSON.stringify(shoppingCart));
addItemToCart(shoppingCart);
console.log("After function call:", JSON.stringify(shoppingCart));
Try it Yourself »

The changes made inside the function persist outside the function because both variables reference the same object in memory.

Tip: To avoid modifying the original object, you can create a shallow copy using Object.assign() or the spread operator (...) before making changes.