Module: Functions and Scope

Parameters

JavaScript Essentials: Functions and Scope - Parameters

Parameters are fundamental to creating reusable and flexible functions in JavaScript. They allow you to pass data into a function, enabling the function to operate on different values each time it's called. Here's a breakdown of parameters in JavaScript:

What are Parameters?

  • Placeholders: Parameters are variables listed inside the parentheses () in a function definition. They act as placeholders for the values that will be passed to the function when it's called.
  • Input to Functions: Think of parameters as the "inputs" a function needs to do its job.
  • Local Variables: Parameters are treated as local variables within the function's scope. This means they are only accessible inside the function.

Example:

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

In this example, name is a parameter. The greet function expects to receive a value for name when it's called.

Passing Arguments

  • Arguments: When you call a function, the values you provide are called arguments.
  • Matching Order: Arguments are passed to the function in the order they are listed in the function definition. The first argument corresponds to the first parameter, the second argument to the second parameter, and so on.

Example:

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

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

This will output:

Hello, Alice!
Hello, Bob!

Multiple Parameters

Functions can accept multiple parameters, separated by commas.

Example:

function add(x, y) { // 'x' and 'y' are parameters
  return x + y;
}

let sum = add(5, 3); // 5 is the argument for 'x', 3 is the argument for 'y'
console.log(sum); // Output: 8

Default Parameters

ES6 (ECMAScript 2015) introduced default parameters. If an argument is not provided when calling the function, the parameter will take on a default value.

Example:

function greet(name = "Guest") { // 'name' has a default value of "Guest"
  console.log("Hello, " + name + "!");
}

greet("Charlie"); // Output: Hello, Charlie!
greet();          // Output: Hello, Guest! (uses the default value)

Parameter Destructuring

You can use destructuring to extract values from objects or arrays passed as arguments. This makes your code more concise and readable.

Example (Object Destructuring):

function displayPerson(person) {
  console.log("Name: " + person.name);
  console.log("Age: " + person.age);
}

let person = { name: "David", age: 30 };
displayPerson(person);

// Using destructuring:
function displayPersonDestructured({ name, age }) {
  console.log("Name: " + name);
  console.log("Age: " + age);
}

displayPersonDestructured(person); // Same output

Example (Array Destructuring):

function displayCoordinates([x, y]) {
  console.log("X: " + x);
  console.log("Y: " + y);
}

let coordinates = [10, 20];
displayCoordinates(coordinates);

The arguments Object (Legacy)

Before ES6, there was the arguments object. This is an array-like object available inside all non-arrow functions that contains all the arguments passed to the function, regardless of the number of parameters defined. However, it's generally recommended to use rest parameters (see below) instead.

Example:

function sumAll() {
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

console.log(sumAll(1, 2, 3)); // Output: 6
console.log(sumAll(5, 10, 15, 20)); // Output: 50

Rest Parameters (ES6)

Rest parameters allow you to represent an indefinite number of arguments as an array. They are denoted by the ... syntax.

Example:

function sumAll(...numbers) { // 'numbers' is a rest parameter (an array)
  let total = 0;
  for (let number of numbers) {
    total += number;
  }
  return total;
}

console.log(sumAll(1, 2, 3)); // Output: 6
console.log(sumAll(5, 10, 15, 20)); // Output: 50

Key Differences between arguments and Rest Parameters:

  • arguments is an object: You access arguments using index-based access (e.g., arguments[0]).
  • Rest parameters are an array: You can use array methods directly on the rest parameter (e.g., numbers.forEach()).
  • Rest parameters must be the last parameter: You can't have other parameters after a rest parameter.
  • Rest parameters are more readable and modern.

Summary

Understanding parameters is crucial for writing effective JavaScript functions. By using parameters, default parameters, destructuring, and rest parameters, you can create functions that are flexible, reusable, and easy to understand. Favor rest parameters over the arguments object for modern JavaScript development.