JavaScript and TypeScript course · Module 2: Functions, Arrays and Objects

Function Parameters and Arguments in JavaScript

10 min read ·
In this lesson7

Welcome back to Jurassic Park! In module 1 we learned the basics of functions in JavaScript. Now we will dive into how functions can take in data and work with it - which is key to building flexible and efficient park management systems.

The Difference Between Parameters and Arguments

Although the terms "parameters" and "arguments" are often used interchangeably, there is a subtle difference between them:

  • Parameters are the variables defined in the function declaration
  • Arguments are the actual values passed to the function when it is called
// name and species are parameters
function addDinosaur(name, species) {
  console.log(`Adding a new dinosaur: ${name} (${species})`);
  // Code that adds the dinosaur to the system
}

// "Blue" and "Velociraptor" are arguments
addDinosaur("Blue", "Velociraptor");

Basic Parameters

JavaScript offers several ways to work with function parameters:

1. Required and Optional Parameters

In JavaScript all parameters are technically optional, but we can design functions that treat some parameters as required:

function feedDinosaur(dinoName, foodType) {
  // Check whether the parameters were provided
  if (dinoName === undefined) {
    throw new Error("You must provide the dinosaur's name!");
  }

  // foodType is optional, so we use a default value if it was not provided
  const food = foodType || "meat";

  console.log(`Feeding ${dinoName}, food: ${food}`);
  return `${dinoName} has been fed`;
}

// Calls
feedDinosaur("Rex", "live cattle"); // "Feeding Rex, food: live cattle"
feedDinosaur("Blue"); // "Feeding Blue, food: meat"
// feedDinosaur(); // Error: You must provide the dinosaur's name!

2. Default Parameters (ES6+)

Since ES6 (ES2015), JavaScript has supported default parameters, which make it simpler to define default values:

function scheduleFeeding(dinoName, foodType = "meat", time = "12:00") {
  console.log(`Feeding scheduled for ${dinoName}, food: ${foodType}, time: ${time}`);
  return {
    dino: dinoName,
    food: foodType,
    scheduledTime: time
  };
}

// Calls
scheduleFeeding("Triceratops", "plants", "10:30");
// "Feeding scheduled for Triceratops, food: plants, time: 10:30"

scheduleFeeding("Raptor");
// "Feeding scheduled for Raptor, food: meat, time: 12:00"

scheduleFeeding("Rex", undefined, "15:45");
// "Feeding scheduled for Rex, food: meat, time: 15:45"

Default parameters are evaluated when the function is called, which means you can use expressions and even other parameters:

function prepareEnclosure(dinoType, securityLevel = calculateSecurityLevel(dinoType), capacity = securityLevel * 2) {
  console.log(`Preparing an enclosure for ${dinoType}...`);
  console.log(`Security level: ${securityLevel}`);
  console.log(`Capacity: ${capacity} animals`);
}

function calculateSecurityLevel(dinoType) {
  const dangerousSpecies = ["Tyrannosaurus", "Velociraptor", "Spinosaurus"];
  return dangerousSpecies.includes(dinoType) ? 5 : 3;
}

// Preparing an enclosure for a T-Rex (high security level)
prepareEnclosure("Tyrannosaurus");
// Security level: 5, Capacity: 10 animals

// Preparing an enclosure for a Triceratops (standard security level)
prepareEnclosure("Triceratops");
// Security level: 3, Capacity: 6 animals

// Preparing a custom enclosure
prepareEnclosure("Velociraptor", 6, 4);
// Security level: 6, Capacity: 4 animals

Handling a Variable Number of Arguments

In systems as complex as Jurassic Park, we sometimes need functions that can take a variable number of arguments.

1. The arguments Object

Every regular function (declared with the function keyword) has access to a special arguments object, which contains all the arguments passed to it. Arrow functions do not have their own arguments:

function alertSecurityTeam() {
  console.log(`Sending an alert to ${arguments.length} members of the security team.`);

  for (let i = 0; i < arguments.length; i++) {
    console.log(`Notifying: ${arguments[i]}`);
  }
}

// We can call the function with any number of arguments
alertSecurityTeam("John Hammond", "Robert Muldoon", "Ellie Sattler");
// Sending an alert to 3 members of the security team.
// Notifying: John Hammond
// Notifying: Robert Muldoon
// Notifying: Ellie Sattler

The arguments object is not a real array, but an object that resembles one (an array-like object). You can convert it into an array:

function logVisitors() {
  // Converting arguments into an array
  const visitorsArray = Array.from(arguments);
  // or: const visitorsArray = [...arguments]; // (ES6+)

  console.log(`Logged ${visitorsArray.length} visitors.`);

  // Now we can use array methods
  visitorsArray.forEach((visitor, index) => {
    console.log(`Visitor #${index + 1}: ${visitor}`);
  });
}

logVisitors("Ian Malcolm", "Alan Grant", "Dennis Nedry");
// Logged 3 visitors.
// Visitor #1: Ian Malcolm
// Visitor #2: Alan Grant
// Visitor #3: Dennis Nedry

2. The Rest Parameter (ES6+)

A newer and more elegant way to handle a variable number of arguments is the rest parameter, introduced in ES6:

function trackDinosaurs(...dinosaurs) {
  console.log(`Tracking ${dinosaurs.length} dinosaurs:`);

  dinosaurs.forEach((dino, index) => {
    console.log(`${index + 1}. Locating: ${dino}`);
  });
}

trackDinosaurs("T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus");
// Tracking 4 dinosaurs:
// 1. Locating: T-Rex
// 2. Locating: Velociraptor
// 3. Locating: Triceratops
// 4. Locating: Brachiosaurus

The rest parameter gathers all the remaining arguments into an array. It must be the last parameter of the function, but it can be preceded by regular parameters:

function assignTasks(teamLead, date, ...teamMembers) {
  console.log(`Tasks for ${date} for the team led by ${teamLead}:`);

  teamMembers.forEach(member => {
    console.log(`- ${member}: ${generateRandomTask()}`);
  });
}

function generateRandomTask() {
  const tasks = [
    "Fence inspection",
    "Dinosaur feeding",
    "DNA sample collection",
    "Animal health monitoring",
    "Security system maintenance"
  ];
  return tasks[Math.floor(Math.random() * tasks.length)];
}

assignTasks("Dr. Henry Wu", "2023-06-15", "John", "Sarah", "Michael");
// Tasks for 2023-06-15 for the team led by Dr. Henry Wu:
// - John: Fence inspection
// - Sarah: Dinosaur feeding
// - Michael: Animal health monitoring

The Spread Operator

The spread operator (...) is the opposite of the rest parameter. Instead of gathering arguments into an array, it spreads an array (or another iterable object) out into individual arguments:

function monitorVitalSigns(dinoName, temperature, heartRate, respirationRate) {
  console.log(`Monitoring vital signs for: ${dinoName}`);
  console.log(`- Temperature: ${temperature}°C`);
  console.log(`- Heart rate: ${heartRate} beats/min`);
  console.log(`- Respiration rate: ${respirationRate} breaths/min`);

  // Analyzing the readings and generating a report
  if (temperature > 39 || heartRate > 140 || respirationRate > 30) {
    return "ALERT: Vital signs out of range!";
  }
  return "Vital signs within normal range.";
}

// An array with vital signs data
const rexVitals = ["T-Rex", 38.2, 115, 22];

// Without the spread operator
monitorVitalSigns(rexVitals[0], rexVitals[1], rexVitals[2], rexVitals[3]);

// With the spread operator - it spreads the array into separate arguments
monitorVitalSigns(...rexVitals);

The spread operator is also useful for combining arrays or objects:

// Combining dinosaur data from different systems
const basicDinoData = {
  id: "VLR-01",
  name: "Blue",
  species: "Velociraptor"
};

const healthData = {
  weight: 100,
  health: "Good",
  lastCheckup: "2023-05-10"
};

const behavioralData = {
  temperament: "Aggressive",
  packStatus: "Beta",
  trainingLevel: "Advanced"
};

// Creating a complete dinosaur data object
const completeProfile = {
  ...basicDinoData,
  ...healthData,
  ...behavioralData,
  updatedAt: new Date().toISOString()
};

console.log(completeProfile);
// {
//   id: "VLR-01",
//   name: "Blue",
//   species: "Velociraptor",
//   weight: 100,
//   health: "Good",
//   lastCheckup: "2023-05-10",
//   temperament: "Aggressive",
//   packStatus: "Beta",
//   trainingLevel: "Advanced",
//   updatedAt: "2023-06-15T10:30:00.000Z"
// }

Destructuring Object Parameters

When functions take many parameters, it is often easier to pass them as an object. Destructuring (ES6+) lets you extract those values elegantly:

// A function that accepts an options object
function createDinosaurEnclosure({ species, capacity, securityLevel, location, features = [] }) {
  console.log(`Creating an enclosure for the species: ${species}`);
  console.log(`Capacity: ${capacity} animals`);
  console.log(`Security level: ${securityLevel}/5`);
  console.log(`Location: ${location}`);

  if (features.length > 0) {
    console.log("Additional enclosure features:");
    features.forEach(feature => console.log(`- ${feature}`));
  }

  return `The enclosure for ${species} has been created at location ${location}`;
}

// Calling with an options object
const enclosureResult = createDinosaurEnclosure({
  species: "Triceratops",
  capacity: 6,
  securityLevel: 3,
  location: "Sector B",
  features: ["Water reservoir", "Cretaceous vegetation", "Observation platform"]
});

console.log(enclosureResult);
// "The enclosure for Triceratops has been created at location Sector B"

We can also set default values for the entire object:

function scheduleLabTest({
  specimenId,
  testType = "DNA",
  priority = "Normal",
  assignedTo = "Dr. Wu"
} = {}) {  // The default empty object prevents errors when we pass no argument

  console.log(`Scheduled a ${testType} test for specimen #${specimenId}`);
  console.log(`Priority: ${priority}`);
  console.log(`Assigned to: ${assignedTo}`);

  return `Test scheduled. Test ID: TEST-${specimenId}-${Date.now()}`;
}

// Calling with all the options
scheduleLabTest({
  specimenId: "VLR-42",
  testType: "Genome sequencing",
  priority: "High",
  assignedTo: "Dr. Sattler"
});

// Calling with only the required parameter
scheduleLabTest({ specimenId: "TRX-05" });

// Calling without arguments (works thanks to the default empty object)
// scheduleLabTest(); // Without the default empty object this would throw an error

Practical Example: An Incident Management System

Let's combine the concepts we have learned by building a comprehensive incident management system for Jurassic Park:

// Incident management system
const incidentManager = (function() {
  // Private array of incidents
  const incidents = [];

  // Private helper functions
  function generateIncidentId() {
    return `INC-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
  }

  function notifyTeam(incidentType, location, ...personnel) {
    console.log(`ALERT: Incident of type "${incidentType}" at location "${location}"`);

    if (personnel.length > 0) {
      console.log(`Notifying personnel: ${personnel.join(', ')}`);
    } else {
      console.log("Notifying all security personnel");
    }
  }

  // Public API
  return {
    // Method for reporting a new incident
    reportIncident: function({
      type,
      location,
      description,
      severity = "Medium",
      reportedBy,
      affectedAssets = [],
      notifyPersonnel = []
    }) {
      const incidentId = generateIncidentId();

      const incident = {
        id: incidentId,
        type,
        location,
        description,
        severity,
        reportedBy,
        affectedAssets,
        status: "New",
        reportedAt: new Date().toISOString(),
        resolvedAt: null
      };

      incidents.push(incident);

      // Notifying personnel
      notifyTeam(type, location, ...notifyPersonnel);

      return {
        incidentId,
        message: `Incident #${incidentId} has been registered`
      };
    },

    // Method for updating the status of an incident
    updateIncidentStatus: function(incidentId, newStatus, resolvedBy = null) {
      const incident = incidents.find(inc => inc.id === incidentId);

      if (!incident) {
        return { success: false, message: "Incident not found" };
      }

      incident.status = newStatus;

      if (newStatus === "Resolved") {
        incident.resolvedAt = new Date().toISOString();
        incident.resolvedBy = resolvedBy;
      }

      return {
        success: true,
        message: `Status of incident #${incidentId} updated to "${newStatus}"`
      };
    },

    // Method for retrieving information about an incident
    getIncidentInfo: function(incidentId) {
      const incident = incidents.find(inc => inc.id === incidentId);

      if (!incident) {
        return null;
      }

      return { ...incident }; // We return a copy to avoid modifying the original
    },

    // Method for retrieving a list of incidents by criteria
    getIncidents: function({ status, type, severity, limit = 10 } = {}) {
      let result = [...incidents]; // A copy of the array

      // Filtering by criteria
      if (status) {
        result = result.filter(inc => inc.status === status);
      }

      if (type) {
        result = result.filter(inc => inc.type === type);
      }

      if (severity) {
        result = result.filter(inc => inc.severity === severity);
      }

      // Sorting from newest to oldest
      result.sort((a, b) => new Date(b.reportedAt) - new Date(a.reportedAt));

      // Limiting the results
      return result.slice(0, limit);
    }
  };
})();

// Example use of the system
const breakoutIncident = incidentManager.reportIncident({
  type: "Dinosaur escape",
  location: "Velociraptor Enclosure - Sector C",
  description: "Three velociraptors got out of the enclosure. Park staff evacuated.",
  severity: "Critical",
  reportedBy: "Robert Muldoon",
  affectedAssets: ["VLR-02", "VLR-03", "VLR-04"],
  notifyPersonnel: ["Dr. Grant", "John Hammond", "Ellie Sattler", "Ian Malcolm"]
});

console.log(breakoutIncident.message);
// "Incident #INC-1623844529123-456 has been registered"

// Updating the incident status
const updateResult = incidentManager.updateIncidentStatus(
  breakoutIncident.incidentId,
  "In progress",
  "SWAT team"
);
console.log(updateResult.message);
// "Status of incident #INC-1623844529123-456 updated to "In progress""

// Retrieving information about the incident
const incidentDetails = incidentManager.getIncidentInfo(breakoutIncident.incidentId);
console.log(incidentDetails);

// Searching for incidents by criteria
const criticalIncidents = incidentManager.getIncidents({
  severity: "Critical",
  limit: 5
});
console.log(`Found ${criticalIncidents.length} critical incidents`);

This example demonstrates:

  1. Using object destructuring to receive function parameters
  2. Applying default parameters
  3. Using the rest parameter to handle a variable number of arguments
  4. Using the spread operator to pass arguments
  5. Advanced processing and filtering of data based on parameters

Summary

Functions in JavaScript offer many powerful mechanisms for working with parameters and arguments, which let you create flexible, readable and easy-to-use APIs:

  • Default parameters simplify the handling of optional arguments
  • The rest parameter lets functions take a variable number of arguments
  • The spread operator lets you pass array elements as separate arguments
  • Object destructuring makes working with many parameters easier by organizing them into objects

Thanks to these mechanisms we can create functions that are flexible yet simple to use - which is key to managing complicated systems such as our virtual Jurassic Park.

Arrow functions, which bring a more concise syntax and special behavior regarding the this context, get a separate lesson of their own in this module.

Code for this lesson: index.js
// Function parameters and arguments - Jurassic Park
console.log("Jurassic Park Function Laboratory");
console.log("Managing dinosaurs through functions with parameters\n");

// ===========================================
// 1. BASIC FUNCTIONS WITH PARAMETERS
// ===========================================
console.log("=== 1. Functions with parameters ===");

// Function with a single parameter
function feedDinosaur(dinoName) {
  console.log(`Feeding dinosaur: ${dinoName}`);
}

feedDinosaur("T-Rex");
feedDinosaur("Velociraptor");

// Function with multiple parameters
function addDinosaur(name, species, age, weight) {
  console.log(`\nAdding a new dinosaur to the system:`);
  console.log(`  Name: ${name}`);
  console.log(`  Species: ${species}`);
  console.log(`  Age: ${age} years`);
  console.log(`  Weight: ${weight} kg`);
}

addDinosaur("Blue", "Velociraptor", 5, 80);
addDinosaur("Rexy", "Tyrannosaurus Rex", 8, 8000);

// ===========================================
// 2. DEFAULT PARAMETERS (ES6)
// ===========================================
console.log("\n=== 2. Default parameters ===");

function scheduleFeeding(dinoName, foodType = "meat", time = "12:00") {
  console.log(`Feeding scheduled for ${dinoName}`);
  console.log(`   Food: ${foodType}, Time: ${time}`);
}

scheduleFeeding("Triceratops", "plants", "10:30");
scheduleFeeding("Raptor"); // Will use default values
scheduleFeeding("Rex", undefined, "15:45"); // Skip middle parameter

// Expressions as default values
function createPaddock(paddockNumber, capacity = paddockNumber * 2) {
  console.log(`Creating paddock #${paddockNumber} with capacity ${capacity}`);
}

createPaddock(5);
createPaddock(3, 10);

// ===========================================
// 3. REST PARAMETERS (...args)
// ===========================================
console.log("\n=== 3. Rest parameters (...) ===");

function feedMultipleDinosaurs(...dinoNames) {
  console.log(`Feeding ${dinoNames.length} dinosaurs:`);
  dinoNames.forEach((name, index) => {
    console.log(`  ${index + 1}. ${name}`);
  });
}

feedMultipleDinosaurs("Rex", "Blue", "Charlie", "Delta");
feedMultipleDinosaurs("Triceratops", "Stegosaurus");

// Rest parameter with other parameters
function assignToTeam(teamLeader, ...teamMembers) {
  console.log(`\nTeam led by: ${teamLeader}`);
  console.log(`   Team members: ${teamMembers.join(", ")}`);
}

assignToTeam("Dr. Grant", "Ellie", "Ian", "Lex", "Tim");

// ===========================================
// 4. DESTRUCTURING PARAMETERS
// ===========================================
console.log("\n=== 4. Destructuring in parameters ===");

// Object destructuring
function displayDinosaurInfo({ name, species, age, weight, carnivore }) {
  console.log(`\nInfo about the dinosaur:`);
  console.log(`  Name: ${name}`);
  console.log(`  Species: ${species}`);
  console.log(`  Age: ${age} years`);
  console.log(`  Weight: ${weight} kg`);
  console.log(`  Type: ${carnivore ? "Carnivore" : "Herbivore"}`);
}

const dino = {
  name: "Blue",
  species: "Velociraptor",
  age: 5,
  weight: 80,
  carnivore: true
};

displayDinosaurInfo(dino);

// Destructuring with default values
function createEnclosure({ size = 100, type = "standard", security = "medium" } = {}) {
  console.log(`\nCreating fence:`);
  console.log(`  Size: ${size} m²`);
  console.log(`  Type: ${type}`);
  console.log(`  Security: ${security}`);
}

createEnclosure({ size: 200, type: "high-security", security: "maximum" });
createEnclosure({ size: 150 });
createEnclosure(); // All default values

// Destructuring arrays
function assignPaddocks([first, second, third]) {
  console.log(`\nAssigning paddocks:`);
  console.log(`  Paddock A: ${first}`);
  console.log(`  Paddock B: ${second}`);
  console.log(`  Paddock C: ${third}`);
}

assignPaddocks(["T-Rex", "Triceratops", "Stegosaurus"]);

// ===========================================
// 5. RETURN VALUES
// ===========================================
console.log("\n=== 5. Returning values ===");

function calculateDangerLevel(species, age, aggression) {
  let dangerScore = 0;

  if (species === "Tyrannosaurus") dangerScore += 50;
  else if (species === "Velociraptor") dangerScore += 40;
  else if (species === "Triceratops") dangerScore += 20;
  else dangerScore += 10;

  dangerScore += age * 2;
  dangerScore += aggression * 10;

  let level = "Low";
  if (dangerScore > 80) level = "Extreme";
  else if (dangerScore > 60) level = "High";
  else if (dangerScore > 40) level = "Medium";

  return {
    score: dangerScore,
    level: level,
    recommendation: dangerScore > 70 ? "Double security" : "Standard security"
  };
}

const trexDanger = calculateDangerLevel("Tyrannosaurus", 8, 9);
console.log("T-Rex danger level:", trexDanger);

const triDanger = calculateDangerLevel("Triceratops", 5, 3);
console.log("Triceratops danger level:", triDanger);

// ===========================================
// 6. FUNCTIONS RETURNING FUNCTIONS
// ===========================================
console.log("\n=== 6. Higher-order functions ===");

function createFeeder(foodType) {
  return function(dinoName) {
    console.log(`Feeding ${dinoName} using: ${foodType}`);
  };
}

const meatFeeder = createFeeder("fresh meat");
const plantFeeder = createFeeder("plants");

meatFeeder("T-Rex");
meatFeeder("Velociraptor");
plantFeeder("Triceratops");
plantFeeder("Brachiosaurus");

// ===========================================
// 7. CALLBACK FUNCTIONS
// ===========================================
console.log("\n=== 7. Callback functions ===");

function processDinosaurs(dinosaurs, callback) {
  console.log("\nProcessing dinosaur list:");
  dinosaurs.forEach((dino, index) => {
    callback(dino, index);
  });
}

const dinoList = ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus"];

processDinosaurs(dinoList, (dino, index) => {
  console.log(`  ${index + 1}. ${dino} - Health check:`);
});

// ===========================================
// 8. ARGUMENTS OBJECT (Legacy)
// ===========================================
console.log("\n=== 8. Arguments object (legacy method) ===");

function feedAll() {
  console.log(`Feeding ${arguments.length} dinosaurs:`);
  for (let i = 0; i < arguments.length; i++) {
    console.log(`  ${i + 1}. ${arguments[i]}`);
  }
}

feedAll("Rex", "Blue", "Charlie", "Delta", "Echo");

// ===========================================
// 9. COMPLEX EXAMPLE
// ===========================================
console.log("\n=== 9. Park management system - complex example ===");

function managePark({
  dinosaurs = [],
  visitors = 0,
  weather = "sunny",
  securityLevel = "medium"
} = {}) {
  console.log("\nJURASSIC PARK REPORT");
  console.log("================================");
  console.log(`Dinosaurs in the park: ${dinosaurs.length}`);
  console.log(`Number of visitors: ${visitors}`);
  console.log(`Weather: ${weather}`);
  console.log(`Security level: ${securityLevel}`);

  if (dinosaurs.length > 0) {
    console.log("\nDinosaur list:");
    dinosaurs.forEach((dino, idx) => {
      console.log(`  ${idx + 1}. ${dino.name} (${dino.species})`);
    });
  }

  const isOpen = weather === "sunny" && securityLevel !== "low";
  console.log(`\nPark status: ${isOpen ? "OPEN" : "CLOSED"}`);

  return {
    isOperational: isOpen,
    totalDinosaurs: dinosaurs.length,
    capacity: visitors,
    status: isOpen ? "Operational" : "Closed"
  };
}

const parkStatus = managePark({
  dinosaurs: [
    { name: "Rexy", species: "T-Rex" },
    { name: "Blue", species: "Velociraptor" },
    { name: "Trike", species: "Triceratops" }
  ],
  visitors: 1500,
  weather: "sunny",
  securityLevel: "high"
});

console.log("\nSummary:", parkStatus);

console.log("\nCongratulations! You've mastered function parameters and arguments!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which use of a template literal is correct?

  2. 2. What will typeof null return in JavaScript?

  3. 3. How do you correctly create a BigInt representing the number of years since the dinosaurs went extinct?

  4. 4. What is the main characteristic of the Symbol type in JavaScript?

  5. 5. Which keywords create block-scoped variables?

Hands-on tasks in the game

  • Click in order

    Sort the variable declaration keywords from the least to the most restrictive:

  • Horizontal ordering

    Arrange the elements of calling the toUpperCase method on a string:

  • Click in order

    Arrange the lifecycle of a variable in JavaScript:

  1. QuestionTemplate Literals
  2. QuestionChecking Types with typeof
  3. QuestionBigInt Data Type
  4. Click in orderVariable Declaration Order
  5. QuestionSymbol Data Type
  6. QuestionVariable Scope
  7. Put in orderString Method Syntax
  8. Click in orderVariable Lifecycle

Useful articles