Back to JavaScript
2026-02-087 min read

Keyed collections (JavaScript)

Learn Keyed collections (JavaScript) step by step with clear examples and exercises.

Title: Mastering Keyed Collections (JavaScript) - Organizing Data with Objects and Arrays

Why This Matters

Keyed collections are a fundamental aspect of JavaScript programming, enabling developers to organize complex data structures effectively. Understanding keyed collections is crucial for writing efficient code, debugging issues, and acing interviews. In this lesson, we will delve into the world of objects and arrays in JavaScript, learning how to create, manipulate, and use them for various real-world scenarios.

Prerequisites

To get the most out of this lesson, you should have a basic understanding of:

  1. Variables and data types in JavaScript
  2. Basic control structures (if-else, loops)
  3. Functions and function declarations
  4. Callbacks and higher-order functions
  5. ES6 features such as arrow functions, template literals, and destructuring assignment

Core Concept

Objects

An object is a collection of key-value pairs, where each key uniquely identifies a value. In JavaScript, objects are created using curly braces {} or the Object() constructor.

let person = {
name: "John Doe",
age: 30,
occupation: "Software Engineer"
};

In this example, we have created an object named person with three properties: name, age, and occupation. To access the values of these properties, you can use dot notation (e.g., person.name) or bracket notation (e.g., person["name"]).

Creating Objects with Constructors

You can also create objects using constructors by extending the built-in Object constructor:

function Person(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}

let john = new Person("John Doe", 30, "Software Engineer");

In this example, we have created a constructor called Person that accepts three parameters and initializes the properties of an object with those values. We then create an instance of the Person constructor using the new keyword and assign it to the variable john.

Accessing and Modifying Object Properties

To access or modify the properties of an object, you can use either dot notation or bracket notation:

console.log(person.name); // Output: "John Doe"
person.age = 31;
console.log(person.age); // Output: 31

Object Methods

Objects can also have methods, which are functions associated with the object. To add a method to an object, simply define it as a property with a function value:

let person = {
name: "John Doe",
age: 30,
occupation: "Software Engineer",

sayName: function() {
console.log(this.name);
}
};

person.sayName(); // Output: "John Doe"

Object Destructuring

ES6 introduced object destructuring, which allows you to extract properties from an object and assign them to variables in a concise manner:

let { name, age } = person;
console.log(name); // Output: "John Doe"
console.log(age); // Output: 30

Arrays

An array is a collection of values, each identified by an index starting at 0. In JavaScript, arrays are created using square brackets [] or the Array() constructor.

let numbers = [1, 2, 3, 4, 5];
console.log(numbers[0]); // Output: 1

Accessing and Modifying Array Elements

To access or modify the elements of an array, you can use index notation:

let numbers = [1, 2, 3, 4, 5];
numbers[0] = 10;
console.log(numbers); // Output: [10, 2, 3, 4, 5]

Array Methods

Arrays in JavaScript have a rich set of built-in methods for manipulating and querying data. Some commonly used array methods include:

  • push(): Adds an element to the end of the array and returns the new length
  • pop(): Removes the last element from the array and returns it
  • unshift(): Adds an element to the beginning of the array and returns the new length
  • shift(): Removes the first element from the array and returns it
  • indexOf(): Returns the index of a specified element or -1 if not found
  • forEach(): Executes a provided function on each element in the array
  • map(): Creates a new array with the results of calling a provided function on every element in the original array
  • filter(): Creates a new array with all elements that pass the test implemented by the provided function
  • reduce(): Applies a function against an accumulator and each element in the array to reduce it to a single output value
let numbers = [1, 2, 3, 4, 5];
numbers.push(6);
console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]

let removedNumber = numbers.pop();
console.log(removedNumber); // Output: 6

Worked Example

In this example, we will create a simple address book application using objects and arrays in JavaScript.

// Create an array to store contacts
let contacts = [];

// Add a new contact to the array
contacts.push({
name: "John Doe",
phone: "555-1234",
email: "john.doe@example.com"
});

// Access and display the name of the first contact
console.log(contacts[0].name); // Output: "John Doe"

// Add another contact to the array
contacts.push({
name: "Jane Smith",
phone: "555-5678",
email: "jane.smith@example.com"
});

// Iterate through the contacts and display their names
contacts.forEach(function(contact) {
console.log(contact.name);
});

// Find the index of a contact by name and update their phone number
let johnIndex = contacts.findIndex(function(contact) {
return contact.name === "John Doe";
});

contacts[johnIndex].phone = "555-9876";
console.log(contacts); // Output: [ { name: 'John Doe', phone: '555-9876', email: 'john.doe@example.com' }, { name: 'Jane Smith', phone: '555-5678', email: 'jane.smith@example.com' } ]

Common Mistakes

  1. Forgetting to initialize an object or array before using it
  2. Using the wrong notation (dot vs bracket) to access properties or elements
  3. Misunderstanding the difference between objects and arrays
  4. Not properly handling undefined values when accessing non-existent properties or elements
  5. Overusing global variables instead of defining local variables within functions
  6. Forgetting to return a value from a function when expected
  7. Using == instead of === for comparison, leading to unexpected results due to type coercion
  8. Not understanding the difference between strict mode and non-strict mode in JavaScript
  9. Misusing or misapplying ES6 features such as arrow functions, template literals, and destructuring assignment
  10. Failing to properly handle errors and exceptions in code

Practice Questions

  1. Create an object representing a car with properties for make, model, year, color, and number of doors. Add methods to start the engine and accelerate.
  2. Write a function that takes an array of numbers as input and returns the sum of all even numbers in the array.
  3. Given the following array of objects representing people, write a function that finds the person with the oldest age:
let people = [
{ name: "John Doe", age: 30 },
{ name: "Jane Smith", age: 25 },
{ name: "Mike Johnson", age: 40 }
];

FAQ

What is the difference between an object and an array in JavaScript?

  • An object is a collection of key-value pairs, while an array is a collection of values indexed by number.

How can I create an empty array or object in JavaScript?

  • To create an empty array, use []. To create an empty object, use {} or the Object() constructor.

What happens when you try to access a non-existent property or element in JavaScript?

  • If you try to access a non-existent property on an object or array, JavaScript will return undefined.

How can I loop through the elements of an array in JavaScript?

  • You can use the built-in forEach() method to iterate through the elements of an array. Alternatively, you can use a for loop or a while loop for more control over the iteration.

What is the purpose of the this keyword in JavaScript?

  • The this keyword refers to the object that a function is called on. It helps you access and modify properties and methods of the object within the function.

How can I check if an array contains a specific value in JavaScript?

  • You can use the built-in indexOf() method or the spread operator (...) with the includes() method to check if an array contains a specific value.

What is the difference between shallow copying and deep copying in JavaScript?

  • Shallow copying creates a new object that references the same properties as the original object, while deep copying creates a new object where each property is copied recursively.

How can I merge two arrays in JavaScript?

  • You can use the spread operator (...) to combine two arrays into a new array, or you can use the concat() method to create a new array that includes the elements of both original arrays.

What is the purpose of the let, const, and var keywords in JavaScript?

  • The let keyword declares a block-scoped variable, the const keyword declares a block-scoped constant (immutable variable), and the var keyword declares a function-scoped variable.

How can I handle errors and exceptions in JavaScript?

  • You can use try-catch blocks to catch and handle exceptions, or you can use error objects to handle specific types of errors. Additionally, you can use assertions to validate input data and prevent unexpected behavior.
Keyed collections (JavaScript) | JavaScript | XQA Learn