1. What is a Map in JavaScript?
Answer:
Explanation:
In JavaScript, a Map is a collection of elements where each element is stored as a key-value pair. Maps allow efficient retrieval, addition, and deletion of elements based on their keys.
2. How do you create a new Map in JavaScript?
Answer:
Explanation:
A Map is created using the new Map() constructor.
3. How can you add key-value pairs to a Map in JavaScript?
Answer:
Explanation:
The set method is used to add key-value pairs to a Map.
4. What method do you use to retrieve a value from a Map in JavaScript?
Answer:
Explanation:
The get method is used to retrieve the value associated with a specific key from a Map.
5. How can you remove a key-value pair from a Map in JavaScript?
Answer:
Explanation:
The delete method is used to remove a key-value pair from a Map based on the key.
6. What does the size property of a Map object represent?
Answer:
Explanation:
The size property of a Map object returns the number of key-value pairs it contains.
7. Can a JavaScript Map contain functions as keys or values?
Answer:
Explanation:
In a Map, both keys and values can be of any data type, including functions.
8. How do you check if a Map contains a specific key in JavaScript?
Answer:
Explanation:
The has method is used to check if a Map contains a particular key.
9. What happens if you set a new value for an existing key in a Map?
Answer:
Explanation:
In a Map, if you set a new value for an existing key, the old value is replaced by the new value.
10. How can you iterate over the entries in a Map?
Answer:
Explanation:
You can iterate over the entries in a Map using the forEach method or a for loop (e.g., for…of loop).
11. What is the purpose of the clear method in a Map?
Answer:
Explanation:
The clear method is used to remove all key-value pairs from a Map, effectively clearing it.
12. Can a JavaScript Map have non-string keys?
Answer:
Explanation:
Unlike objects, where keys must be strings or symbols, Map keys can be of any type, including numbers, functions, and objects.
13. What is the result of calling myMap.get(nonExistentKey) in JavaScript?
Answer:
Explanation:
If you use the get method to retrieve the value of a key that does not exist in the Map, it returns undefined.
14. Is the order of key-value pairs preserved in a JavaScript Map?
Answer:
Explanation:
Unlike objects, the order of key-value pairs in a Map is preserved in the order they were inserted.
15. How can you convert a Map to an Array in JavaScript?
Answer:
Explanation:
A Map can be converted to an Array using Array.from(myMap) or the spread operator […myMap].