hasSessionStorageKey
Checks if a specific key exists in sessionStorage.
1/**
2 * Checks if a specific key exists in sessionStorage.
3 *
4 * @param key - The key to check for existence.
5 * @returns True if the key exists, false otherwise.
6 */
7export function hasSessionStorageKey(key: string): boolean {
8 return sessionStorage.getItem(key) !== null;
9}
Simple and Direct
Provides a clean and intuitive way to check for the presence of a key without retrieving or parsing its value.
Efficient Key Existence Check
Leverages
sessionStorage.getItem
internally, which is performant and widely supported across browsers.Reduces Redundant Logic
Eliminates the need to write repetitive
getItem
+ null-check code throughout your app.
Tests | Examples
1const key = 'testKey';
2
3beforeEach(() => {
4 sessionStorage.clear();
5});
6
7test('returns true if key exists in sessionStorage', () => {
8 sessionStorage.setItem(key, 'value');
9 expect(hasSessionStorageKey(key)).toBe(true);
10});
11
12test('returns false if key does not exist in sessionStorage', () => {
13 expect(hasSessionStorageKey('missingKey')).toBe(false);
14});
15
16test('returns true for existing key with null string value', () => {
17 sessionStorage.setItem(key, 'null');
18 expect(hasSessionStorageKey(key)).toBe(true);
19});
20
21test('returns true for existing key with empty string value', () => {
22 sessionStorage.setItem(key, '');
23 expect(hasSessionStorageKey(key)).toBe(true);
24});
Common Use Cases
Conditional Logic Based on Session Data
Determine if a feature should be enabled or a warning shown based on stored flags.
Authentication or Onboarding Checks
Verify if session tokens or onboarding markers are stored before proceeding.
Selective Initialization
Load or skip logic paths depending on whether temporary session values exist.
Debugging or Feature Flags
Check for debug flags or feature toggles set in the current session.