The has()
method returns a boolean indicating whether a key exists in a Map. It is a direct and efficient way to check for the presence of a key without retrieving the actual value.
Example 1: Checking for a User
// A Map storing user permissions.
const userPermissions = new Map([
['Alice', 'read-write'],
['Bob', 'read-only']
]);
// Check if a permission entry exists for 'Alice'.
const hasAlice = userPermissions.has('Alice');
console.log(hasAlice); // Outputs: true
Explanation
This code uses has()
to confirm that the key 'Alice' is present in the userPermissions
Map, returning true
.
Example 2: Verifying a Product in Inventory
// A Map representing product stock, with IDs as keys.
const productStock = new Map([
[1001, 12],
[1002, 5]
]);
// Check if product ID 1003 is in our stock records.
const hasProduct1003 = productStock.has(1003);
console.log(hasProduct1003); // Outputs: false
Explanation
Here, has()
checks for the key 1003
. Since this key does not exist in the productStock
Map, the method correctly returns false
.
Example 3: Conditional Logic with has()
// A Map of cached API responses.
const apiCache = new Map();
const cacheKey = '/api/users';
// Only perform an action if a key exists.
if (apiCache.has(cacheKey)) {
console.log('Cache hit!');
} else {
console.log('Cache miss. Fetching from API...');
}
Explanation
This example shows a common use case for has()
: checking for a key's existence before proceeding with further logic, preventing unnecessary operations.
Example 4: Distinguishing undefined
Value from a Non-Existent Key
// A Map where a key might explicitly have an undefined value.
const settings = new Map();
settings.set('user', undefined);
// Using get() would be ambiguous here.
console.log(settings.get('user')); // Outputs: undefined
console.log(settings.get('theme')); // Outputs: undefined
// has() provides a clear distinction.
console.log(settings.has('user')); // Outputs: true
console.log(settings.has('theme')); // Outputs: false
Explanation
This demonstrates a key difference between get()
and has()
. While get()
returns undefined
for both a non-existent key and a key with an undefined
value, has()
accurately confirms if the key itself is present.
Example 5: Checking with an Object Key
// A Map using objects as keys.
const styleConfig = new Map();
const boldStyle = { fontWeight: 'bold' };
styleConfig.set(boldStyle, 'CSS-Class-1');
// Check for the existence of the key using the same object reference.
const hasBoldStyle = styleConfig.has(boldStyle);
console.log(hasBoldStyle); // Outputs: true
Explanation
When using objects as keys, has()
checks for the key by reference. It returns true
only if the exact same object instance is passed to it.
Example 6: Guarding Against Duplicate Entries
// A Map to store unique session IDs.
const activeSessions = new Map();
const newSessionId = 'xyz-789';
// Add a new session only if it's not already active.
if (!activeSessions.has(newSessionId)) {
activeSessions.set(newSessionId, { startTime: Date.now() });
console.log('New session started.');
}
Explanation
This code uses has()
as a guard to prevent adding a duplicate entry. It ensures that a new session is only created if its ID isn't already in the Map.
Example 7: Checking for NaN
as a Key
// Maps can correctly handle NaN as a key.
const specialValues = new Map();
specialValues.set(NaN, 'Not a Number');
// Check for the NaN key.
const hasNaNKey = specialValues.has(NaN);
console.log(hasNaNKey); // Outputs: true
Explanation
Unlike most collections in JavaScript, a Map treats all NaN
values as the same key. The has()
method correctly identifies the presence of a NaN
key.