Imagine you want to store and quickly find phone numbers by name. You have two options: a list of pairs (name, number) or a hash map. Why is a hash map better for this?
Think about how long it takes to find an item in a list versus a hash map.
A hash map uses a special function to jump directly to the location of the key, so it finds values quickly. A list must check each item until it finds the key, which takes longer as the list grows.
Consider this JavaScript code using a Map to store fruit colors. What will it print?
const fruitColors = new Map(); fruitColors.set('apple', 'red'); fruitColors.set('banana', 'yellow'); fruitColors.set('grape', 'purple'); console.log(fruitColors.get('banana'));
Look at what value is stored with the key 'banana'.
The Map stores 'banana' with the value 'yellow'. The get method returns the value for the key.
What will this code print or error?
const map = {a: 1, b: 2}; console.log(map['c'].toString());
What happens if you try to call a method on undefined?
Accessing map['c'] returns undefined because 'c' is not a key. Calling toString() on undefined causes a TypeError.
When you have thousands of items, searching for one by scanning all items is slow. How does a hash map solve this problem?
Think about how a hash function helps find the place to look.
A hash map uses a hash function to quickly find the storage location for a key, so it does not need to check every item.
You want to count how many times each word appears in a large text. Which data structure is best to store and update counts efficiently?
Think about fast lookup and update by word.
A hash map allows fast lookup and update of counts by word key, making it ideal for frequency counting.
