JavaScript Function Parameters
JavaScript Basics

JavaScript Function Parameters

Function parameters

Understanding JavaScript Function Parameters and Arguments

JavaScript functions offer flexible handling of parameters and arguments, allowing you to pass any number of arguments without type or count restrictions.

Function Parameters vs. Arguments

  • Parameters are variables specified in the function definition.
  • Arguments are the actual values passed to the function.
function calculateArea(width, height) {  return width * height;}

In this function, width and height are parameters.

Parameter Rules in JavaScript

  • JavaScript does not enforce data types for parameters.
  • There is no type checking on arguments passed to a function.
  • The function does not automatically check the number of arguments received.

Handling Default Parameters

In cases where arguments are missing, their corresponding parameters default to undefined. ES6 introduced a syntax for setting default values to parameters directly in the function signature.

function greet(name, greeting = "Hello") {  return `${greeting}, ${name}!`;}

This function assigns "Hello" as a default greeting if none is provided.

Rest Parameter Syntax

The rest parameter syntax allows functions to accept an indefinite number of arguments as an array.

function sum(...numbers) {

  return numbers.reduce((total, num) => total + num, 0);

}

Here, numbers is an array holding all arguments passed to the sum function.

The arguments Object

Every JavaScript function can access the arguments object, an array-like object containing all passed arguments.

function findMax() {  let max = -Infinity;  
for (let i = 0; i < arguments.length; i++) {    if (arguments[i] > max) {      max = arguments[i];    }  }  return max;}‍

This function iterates over arguments to find the maximum value.

Value vs. Reference

  • Primitive values (like numbers and strings) are passed to functions by value.
  • Objects are passed by reference, or more accurately, by sharing the reference.

function updateMessage(obj) {  obj.message = "New Message";}const myObj = { message: "Original Message" };updateMessage(myObj);console.log(myObj.message);  // Outputs "New Message"

In this example, changes to the object property within the function affect the original object because the object reference is shared.

Summary

JavaScript's function parameter and argument handling are designed for flexibility, allowing functions to operate on varied numbers of inputs effectively. Using default parameters, rest parameters, and the arguments object can greatly enhance this flexibility. Meanwhile, understanding the difference between passing by value and by reference is crucial for managing how data is manipulated within functions.

Take a look into your desired course