Imagine you want to store and quickly find phone numbers by name. You can use a list of pairs or a hash map. Why is a hash map better for this?
Think about how long it takes to find a phone number in a list versus a hash map.
Hash maps use a special function to jump directly to the data location, making search very fast. Lists require checking each element until the key is found, which is slower.
Consider this TypeScript code using a hash map (object) to store ages by name. What is printed?
const ages: {[key: string]: number} = {};
ages['Alice'] = 30;
ages['Bob'] = 25;
ages['Alice'] = 35;
console.log(ages['Alice']);What happens when you assign a value to the same key twice?
Assigning a new value to an existing key in a hash map updates the value. So 'Alice' age changes from 30 to 35.
Look at this TypeScript code. Why does accessing ages['Charlie'] return undefined?
const ages: {[key: string]: number} = { 'Alice': 30, 'Bob': 25 };
console.log(ages['Charlie']);Check if the key you are looking for is present in the hash map.
Accessing a key that does not exist in a hash map returns undefined in JavaScript/TypeScript.
Given this TypeScript code, what is printed after deleting a key?
const map: {[key: string]: number} = { 'x': 10, 'y': 20 }; delete map['x']; console.log(map);
What does the delete operator do to a key in an object?
The delete operator removes the key and its value from the object, so only 'y' remains.
When working with large datasets, why is a hash map preferred over arrays for key-based data retrieval?
Think about how long it takes to find an item by key in an array versus a hash map.
Hash maps use a hashing function to jump directly to the data location, making operations very fast even for large data. Arrays require checking each element, which is slower as data grows.
