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
1// name and species are parameters
2function addDinosaur(name, species) {
3  console.log(`Adding a new dinosaur: ${name} (${species})`);
4  // Code that adds the dinosaur to the system
5}
6
7// "Blue" and "Velociraptor" are arguments
8addDinosaur("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:

1function feedDinosaur(dinoName, foodType) {
2  // Check whether the parameters were provided
3  if (dinoName === undefined) {
4    throw new Error("You must provide the dinosaur's name!");
5  }
6
7  // foodType is optional, so we use a default value if it was not provided
8  const food = foodType || "meat";
9
10  console.log(`Feeding ${dinoName}, food: ${food}`);
11  return `${dinoName} has been fed`;
12}
13
14// Calls
15feedDinosaur("Rex", "live cattle"); // "Feeding Rex, food: live cattle"
16feedDinosaur("Blue"); // "Feeding Blue, food: meat"
17// 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:

1function scheduleFeeding(dinoName, foodType = "meat", time = "12:00") {
2  console.log(`Feeding scheduled for ${dinoName}, food: ${foodType}, time: ${time}`);
3  return {
4    dino: dinoName,
5    food: foodType,
6    scheduledTime: time
7  };
8}
9
10// Calls
11scheduleFeeding("Triceratops", "plants", "10:30");
12// "Feeding scheduled for Triceratops, food: plants, time: 10:30"
13
14scheduleFeeding("Raptor");
15// "Feeding scheduled for Raptor, food: meat, time: 12:00"
16
17scheduleFeeding("Rex", undefined, "15:45");
18// "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:

1function prepareEnclosure(dinoType, securityLevel = calculateSecurityLevel(dinoType), capacity = securityLevel * 2) {
2  console.log(`Preparing an enclosure for ${dinoType}...`);
3  console.log(`Security level: ${securityLevel}`);
4  console.log(`Capacity: ${capacity} animals`);
5}
6
7function calculateSecurityLevel(dinoType) {
8  const dangerousSpecies = ["Tyrannosaurus", "Velociraptor", "Spinosaurus"];
9  return dangerousSpecies.includes(dinoType) ? 5 : 3;
10}
11
12// Preparing an enclosure for a T-Rex (high security level)
13prepareEnclosure("Tyrannosaurus");
14// Security level: 5, Capacity: 10 animals
15
16// Preparing an enclosure for a Triceratops (standard security level)
17prepareEnclosure("Triceratops");
18// Security level: 3, Capacity: 6 animals
19
20// Preparing a custom enclosure
21prepareEnclosure("Velociraptor", 6, 4);
22// 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:

1function alertSecurityTeam() {
2  console.log(`Sending an alert to ${arguments.length} members of the security team.`);
3
4  for (let i = 0; i < arguments.length; i++) {
5    console.log(`Notifying: ${arguments[i]}`);
6  }
7}
8
9// We can call the function with any number of arguments
10alertSecurityTeam("John Hammond", "Robert Muldoon", "Ellie Sattler");
11// Sending an alert to 3 members of the security team.
12// Notifying: John Hammond
13// Notifying: Robert Muldoon
14// 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:

1function logVisitors() {
2  // Converting arguments into an array
3  const visitorsArray = Array.from(arguments);
4  // or: const visitorsArray = [...arguments]; // (ES6+)
5
6  console.log(`Logged ${visitorsArray.length} visitors.`);
7
8  // Now we can use array methods
9  visitorsArray.forEach((visitor, index) => {
10    console.log(`Visitor #${index + 1}: ${visitor}`);
11  });
12}
13
14logVisitors("Ian Malcolm", "Alan Grant", "Dennis Nedry");
15// Logged 3 visitors.
16// Visitor #1: Ian Malcolm
17// Visitor #2: Alan Grant
18// 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:

1function trackDinosaurs(...dinosaurs) {
2  console.log(`Tracking ${dinosaurs.length} dinosaurs:`);
3
4  dinosaurs.forEach((dino, index) => {
5    console.log(`${index + 1}. Locating: ${dino}`);
6  });
7}
8
9trackDinosaurs("T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus");
10// Tracking 4 dinosaurs:
11// 1. Locating: T-Rex
12// 2. Locating: Velociraptor
13// 3. Locating: Triceratops
14// 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:

1function assignTasks(teamLead, date, ...teamMembers) {
2  console.log(`Tasks for ${date} for the team led by ${teamLead}:`);
3
4  teamMembers.forEach(member => {
5    console.log(`- ${member}: ${generateRandomTask()}`);
6  });
7}
8
9function generateRandomTask() {
10  const tasks = [
11    "Fence inspection",
12    "Dinosaur feeding",
13    "DNA sample collection",
14    "Animal health monitoring",
15    "Security system maintenance"
16  ];
17  return tasks[Math.floor(Math.random() * tasks.length)];
18}
19
20assignTasks("Dr. Henry Wu", "2023-06-15", "John", "Sarah", "Michael");
21// Tasks for 2023-06-15 for the team led by Dr. Henry Wu:
22// - John: Fence inspection
23// - Sarah: Dinosaur feeding
24// - 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:

1function monitorVitalSigns(dinoName, temperature, heartRate, respirationRate) {
2  console.log(`Monitoring vital signs for: ${dinoName}`);
3  console.log(`- Temperature: ${temperature}ยฐC`);
4  console.log(`- Heart rate: ${heartRate} beats/min`);
5  console.log(`- Respiration rate: ${respirationRate} breaths/min`);
6
7  // Analyzing the readings and generating a report
8  if (temperature > 39 || heartRate > 140 || respirationRate > 30) {
9    return "ALERT: Vital signs out of range!";
10  }
11  return "Vital signs within normal range.";
12}
13
14// An array with vital signs data
15const rexVitals = ["T-Rex", 38.2, 115, 22];
16
17// Without the spread operator
18monitorVitalSigns(rexVitals[0], rexVitals[1], rexVitals[2], rexVitals[3]);
19
20// With the spread operator - it spreads the array into separate arguments
21monitorVitalSigns(...rexVitals);

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

1// Combining dinosaur data from different systems
2const basicDinoData = {
3  id: "VLR-01",
4  name: "Blue",
5  species: "Velociraptor"
6};
7
8const healthData = {
9  weight: 100,
10  health: "Good",
11  lastCheckup: "2023-05-10"
12};
13
14const behavioralData = {
15  temperament: "Aggressive",
16  packStatus: "Beta",
17  trainingLevel: "Advanced"
18};
19
20// Creating a complete dinosaur data object
21const completeProfile = {
22  ...basicDinoData,
23  ...healthData,
24  ...behavioralData,
25  updatedAt: new Date().toISOString()
26};
27
28console.log(completeProfile);
29// {
30//   id: "VLR-01",
31//   name: "Blue",
32//   species: "Velociraptor",
33//   weight: 100,
34//   health: "Good",
35//   lastCheckup: "2023-05-10",
36//   temperament: "Aggressive",
37//   packStatus: "Beta",
38//   trainingLevel: "Advanced",
39//   updatedAt: "2023-06-15T10:30:00.000Z"
40// }

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:

1// A function that accepts an options object
2function createDinosaurEnclosure({ species, capacity, securityLevel, location, features = [] }) {
3  console.log(`Creating an enclosure for the species: ${species}`);
4  console.log(`Capacity: ${capacity} animals`);
5  console.log(`Security level: ${securityLevel}/5`);
6  console.log(`Location: ${location}`);
7
8  if (features.length > 0) {
9    console.log("Additional enclosure features:");
10    features.forEach(feature => console.log(`- ${feature}`));
11  }
12
13  return `The enclosure for ${species} has been created at location ${location}`;
14}
15
16// Calling with an options object
17const enclosureResult = createDinosaurEnclosure({
18  species: "Triceratops",
19  capacity: 6,
20  securityLevel: 3,
21  location: "Sector B",
22  features: ["Water reservoir", "Cretaceous vegetation", "Observation platform"]
23});
24
25console.log(enclosureResult);
26// "The enclosure for Triceratops has been created at location Sector B"

We can also set default values for the entire object:

1function scheduleLabTest({
2  specimenId,
3  testType = "DNA",
4  priority = "Normal",
5  assignedTo = "Dr. Wu"
6} = {}) {  // The default empty object prevents errors when we pass no argument
7
8  console.log(`Scheduled a ${testType} test for specimen #${specimenId}`);
9  console.log(`Priority: ${priority}`);
10  console.log(`Assigned to: ${assignedTo}`);
11
12  return `Test scheduled. Test ID: TEST-${specimenId}-${Date.now()}`;
13}
14
15// Calling with all the options
16scheduleLabTest({
17  specimenId: "VLR-42",
18  testType: "Genome sequencing",
19  priority: "High",
20  assignedTo: "Dr. Sattler"
21});
22
23// Calling with only the required parameter
24scheduleLabTest({ specimenId: "TRX-05" });
25
26// Calling without arguments (works thanks to the default empty object)
27// 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:

1// Incident management system
2const incidentManager = (function() {
3  // Private array of incidents
4  const incidents = [];
5
6  // Private helper functions
7  function generateIncidentId() {
8    return `INC-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
9  }
10
11  function notifyTeam(incidentType, location, ...personnel) {
12    console.log(`ALERT: Incident of type "${incidentType}" at location "${location}"`);
13
14    if (personnel.length > 0) {
15      console.log(`Notifying personnel: ${personnel.join(', ')}`);
16    } else {
17      console.log("Notifying all security personnel");
18    }
19  }
20
21  // Public API
22  return {
23    // Method for reporting a new incident
24    reportIncident: function({
25      type,
26      location,
27      description,
28      severity = "Medium",
29      reportedBy,
30      affectedAssets = [],
31      notifyPersonnel = []
32    }) {
33      const incidentId = generateIncidentId();
34
35      const incident = {
36        id: incidentId,
37        type,
38        location,
39        description,
40        severity,
41        reportedBy,
42        affectedAssets,
43        status: "New",
44        reportedAt: new Date().toISOString(),
45        resolvedAt: null
46      };
47
48      incidents.push(incident);
49
50      // Notifying personnel
51      notifyTeam(type, location, ...notifyPersonnel);
52
53      return {
54        incidentId,
55        message: `Incident #${incidentId} has been registered`
56      };
57    },
58
59    // Method for updating the status of an incident
60    updateIncidentStatus: function(incidentId, newStatus, resolvedBy = null) {
61      const incident = incidents.find(inc => inc.id === incidentId);
62
63      if (!incident) {
64        return { success: false, message: "Incident not found" };
65      }
66
67      incident.status = newStatus;
68
69      if (newStatus === "Resolved") {
70        incident.resolvedAt = new Date().toISOString();
71        incident.resolvedBy = resolvedBy;
72      }
73
74      return {
75        success: true,
76        message: `Status of incident #${incidentId} updated to "${newStatus}"`
77      };
78    },
79
80    // Method for retrieving information about an incident
81    getIncidentInfo: function(incidentId) {
82      const incident = incidents.find(inc => inc.id === incidentId);
83
84      if (!incident) {
85        return null;
86      }
87
88      return { ...incident }; // We return a copy to avoid modifying the original
89    },
90
91    // Method for retrieving a list of incidents by criteria
92    getIncidents: function({ status, type, severity, limit = 10 } = {}) {
93      let result = [...incidents]; // A copy of the array
94
95      // Filtering by criteria
96      if (status) {
97        result = result.filter(inc => inc.status === status);
98      }
99
100      if (type) {
101        result = result.filter(inc => inc.type === type);
102      }
103
104      if (severity) {
105        result = result.filter(inc => inc.severity === severity);
106      }
107
108      // Sorting from newest to oldest
109      result.sort((a, b) => new Date(b.reportedAt) - new Date(a.reportedAt));
110
111      // Limiting the results
112      return result.slice(0, limit);
113    }
114  };
115})();
116
117// Example use of the system
118const breakoutIncident = incidentManager.reportIncident({
119  type: "Dinosaur escape",
120  location: "Velociraptor Enclosure - Sector C",
121  description: "Three velociraptors got out of the enclosure. Park staff evacuated.",
122  severity: "Critical",
123  reportedBy: "Robert Muldoon",
124  affectedAssets: ["VLR-02", "VLR-03", "VLR-04"],
125  notifyPersonnel: ["Dr. Grant", "John Hammond", "Ellie Sattler", "Ian Malcolm"]
126});
127
128console.log(breakoutIncident.message);
129// "Incident #INC-1623844529123-456 has been registered"
130
131// Updating the incident status
132const updateResult = incidentManager.updateIncidentStatus(
133  breakoutIncident.incidentId,
134  "In progress",
135  "SWAT team"
136);
137console.log(updateResult.message);
138// "Status of incident #INC-1623844529123-456 updated to "In progress""
139
140// Retrieving information about the incident
141const incidentDetails = incidentManager.getIncidentInfo(breakoutIncident.incidentId);
142console.log(incidentDetails);
143
144// Searching for incidents by criteria
145const criticalIncidents = incidentManager.getIncidents({
146  severity: "Critical",
147  limit: 5
148});
149console.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
1// Function parameters and arguments - Jurassic Park
2console.log("Jurassic Park Function Laboratory");
3console.log("Managing dinosaurs through functions with parameters\n");
4
5// ===========================================
6// 1. BASIC FUNCTIONS WITH PARAMETERS
7// ===========================================
8console.log("=== 1. Functions with parameters ===");
9
10// Function with a single parameter
11function feedDinosaur(dinoName) {
12  console.log(`Feeding dinosaur: ${dinoName}`);
13}
14
15feedDinosaur("T-Rex");
16feedDinosaur("Velociraptor");
17
18// Function with multiple parameters
19function addDinosaur(name, species, age, weight) {
20  console.log(`\nAdding a new dinosaur to the system:`);
21  console.log(`  Name: ${name}`);
22  console.log(`  Species: ${species}`);
23  console.log(`  Age: ${age} years`);
24  console.log(`  Weight: ${weight} kg`);
25}
26
27addDinosaur("Blue", "Velociraptor", 5, 80);
28addDinosaur("Rexy", "Tyrannosaurus Rex", 8, 8000);
29
30// ===========================================
31// 2. DEFAULT PARAMETERS (ES6)
32// ===========================================
33console.log("\n=== 2. Default parameters ===");
34
35function scheduleFeeding(dinoName, foodType = "meat", time = "12:00") {
36  console.log(`Feeding scheduled for ${dinoName}`);
37  console.log(`   Food: ${foodType}, Time: ${time}`);
38}
39
40scheduleFeeding("Triceratops", "plants", "10:30");
41scheduleFeeding("Raptor"); // Will use default values
42scheduleFeeding("Rex", undefined, "15:45"); // Skip middle parameter
43
44// Expressions as default values
45function createPaddock(paddockNumber, capacity = paddockNumber * 2) {
46  console.log(`Creating paddock #${paddockNumber} with capacity ${capacity}`);
47}
48
49createPaddock(5);
50createPaddock(3, 10);
51
52// ===========================================
53// 3. REST PARAMETERS (...args)
54// ===========================================
55console.log("\n=== 3. Rest parameters (...) ===");
56
57function feedMultipleDinosaurs(...dinoNames) {
58  console.log(`Feeding ${dinoNames.length} dinosaurs:`);
59  dinoNames.forEach((name, index) => {
60    console.log(`  ${index + 1}. ${name}`);
61  });
62}
63
64feedMultipleDinosaurs("Rex", "Blue", "Charlie", "Delta");
65feedMultipleDinosaurs("Triceratops", "Stegosaurus");
66
67// Rest parameter with other parameters
68function assignToTeam(teamLeader, ...teamMembers) {
69  console.log(`\nTeam led by: ${teamLeader}`);
70  console.log(`   Team members: ${teamMembers.join(", ")}`);
71}
72
73assignToTeam("Dr. Grant", "Ellie", "Ian", "Lex", "Tim");
74
75// ===========================================
76// 4. DESTRUCTURING PARAMETERS
77// ===========================================
78console.log("\n=== 4. Destructuring in parameters ===");
79
80// Object destructuring
81function displayDinosaurInfo({ name, species, age, weight, carnivore }) {
82  console.log(`\nInfo about the dinosaur:`);
83  console.log(`  Name: ${name}`);
84  console.log(`  Species: ${species}`);
85  console.log(`  Age: ${age} years`);
86  console.log(`  Weight: ${weight} kg`);
87  console.log(`  Type: ${carnivore ? "Carnivore" : "Herbivore"}`);
88}
89
90const dino = {
91  name: "Blue",
92  species: "Velociraptor",
93  age: 5,
94  weight: 80,
95  carnivore: true
96};
97
98displayDinosaurInfo(dino);
99
100// Destructuring with default values
101function createEnclosure({ size = 100, type = "standard", security = "medium" } = {}) {
102  console.log(`\nCreating fence:`);
103  console.log(`  Size: ${size} mยฒ`);
104  console.log(`  Type: ${type}`);
105  console.log(`  Security: ${security}`);
106}
107
108createEnclosure({ size: 200, type: "high-security", security: "maximum" });
109createEnclosure({ size: 150 });
110createEnclosure(); // All default values
111
112// Destructuring arrays
113function assignPaddocks([first, second, third]) {
114  console.log(`\nAssigning paddocks:`);
115  console.log(`  Paddock A: ${first}`);
116  console.log(`  Paddock B: ${second}`);
117  console.log(`  Paddock C: ${third}`);
118}
119
120assignPaddocks(["T-Rex", "Triceratops", "Stegosaurus"]);
121
122// ===========================================
123// 5. RETURN VALUES
124// ===========================================
125console.log("\n=== 5. Returning values ===");
126
127function calculateDangerLevel(species, age, aggression) {
128  let dangerScore = 0;
129
130  if (species === "Tyrannosaurus") dangerScore += 50;
131  else if (species === "Velociraptor") dangerScore += 40;
132  else if (species === "Triceratops") dangerScore += 20;
133  else dangerScore += 10;
134
135  dangerScore += age * 2;
136  dangerScore += aggression * 10;
137
138  let level = "Low";
139  if (dangerScore > 80) level = "Extreme";
140  else if (dangerScore > 60) level = "High";
141  else if (dangerScore > 40) level = "Medium";
142
143  return {
144    score: dangerScore,
145    level: level,
146    recommendation: dangerScore > 70 ? "Double security" : "Standard security"
147  };
148}
149
150const trexDanger = calculateDangerLevel("Tyrannosaurus", 8, 9);
151console.log("T-Rex danger level:", trexDanger);
152
153const triDanger = calculateDangerLevel("Triceratops", 5, 3);
154console.log("Triceratops danger level:", triDanger);
155
156// ===========================================
157// 6. FUNCTIONS RETURNING FUNCTIONS
158// ===========================================
159console.log("\n=== 6. Higher-order functions ===");
160
161function createFeeder(foodType) {
162  return function(dinoName) {
163    console.log(`Feeding ${dinoName} using: ${foodType}`);
164  };
165}
166
167const meatFeeder = createFeeder("fresh meat");
168const plantFeeder = createFeeder("plants");
169
170meatFeeder("T-Rex");
171meatFeeder("Velociraptor");
172plantFeeder("Triceratops");
173plantFeeder("Brachiosaurus");
174
175// ===========================================
176// 7. CALLBACK FUNCTIONS
177// ===========================================
178console.log("\n=== 7. Callback functions ===");
179
180function processDinosaurs(dinosaurs, callback) {
181  console.log("\nProcessing dinosaur list:");
182  dinosaurs.forEach((dino, index) => {
183    callback(dino, index);
184  });
185}
186
187const dinoList = ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus"];
188
189processDinosaurs(dinoList, (dino, index) => {
190  console.log(`  ${index + 1}. ${dino} - Health check:`);
191});
192
193// ===========================================
194// 8. ARGUMENTS OBJECT (Legacy)
195// ===========================================
196console.log("\n=== 8. Arguments object (legacy method) ===");
197
198function feedAll() {
199  console.log(`Feeding ${arguments.length} dinosaurs:`);
200  for (let i = 0; i < arguments.length; i++) {
201    console.log(`  ${i + 1}. ${arguments[i]}`);
202  }
203}
204
205feedAll("Rex", "Blue", "Charlie", "Delta", "Echo");
206
207// ===========================================
208// 9. COMPLEX EXAMPLE
209// ===========================================
210console.log("\n=== 9. Park management system - complex example ===");
211
212function managePark({
213  dinosaurs = [],
214  visitors = 0,
215  weather = "sunny",
216  securityLevel = "medium"
217} = {}) {
218  console.log("\nJURASSIC PARK REPORT");
219  console.log("================================");
220  console.log(`Dinosaurs in the park: ${dinosaurs.length}`);
221  console.log(`Number of visitors: ${visitors}`);
222  console.log(`Weather: ${weather}`);
223  console.log(`Security level: ${securityLevel}`);
224
225  if (dinosaurs.length > 0) {
226    console.log("\nDinosaur list:");
227    dinosaurs.forEach((dino, idx) => {
228      console.log(`  ${idx + 1}. ${dino.name} (${dino.species})`);
229    });
230  }
231
232  const isOpen = weather === "sunny" && securityLevel !== "low";
233  console.log(`\nPark status: ${isOpen ? "OPEN" : "CLOSED"}`);
234
235  return {
236    isOperational: isOpen,
237    totalDinosaurs: dinosaurs.length,
238    capacity: visitors,
239    status: isOpen ? "Operational" : "Closed"
240  };
241}
242
243const parkStatus = managePark({
244  dinosaurs: [
245    { name: "Rexy", species: "T-Rex" },
246    { name: "Blue", species: "Velociraptor" },
247    { name: "Trike", species: "Triceratops" }
248  ],
249  visitors: 1500,
250  weather: "sunny",
251  securityLevel: "high"
252});
253
254console.log("\nSummary:", parkStatus);
255
256console.log("\nCongratulations! You've mastered function parameters and arguments!");

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:

Useful articles