Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

hasLocalStorageKey

Checks if a specific key exists in localStorage.

TypeScript
Copied!
1/**
2 * Checks if a specific key exists in localStorage.
3 *
4 * @param key - The key to check for existence.
5 * @returns True if the key exists, false otherwise.
6 */
7export function hasLocalStorageKey(key: string): boolean {
8  return localStorage.getItem(key) !== null;
9}
  • Lightweight Key Check

    Provides a fast and efficient way to check for key existence without parsing or modifying stored data.

  • Avoids Side Effects

    Pure read-only access — does not alter or mutate localStorage, preserving state integrity.

  • Simplifies Conditional Logic

    Enables cleaner flow control when deciding whether to load or initialize stored values.

  • Zero-Dependency Utility

    Doesn’t rely on additional abstractions or libraries; directly leverages native Web APIs.

Tests | Examples

TypeScript
Copied!
1const key = 'testKey';
2
3beforeEach(() => {
4  localStorage.clear();
5});
6
7test('returns true if key exists in localStorage', () => {
8  localStorage.setItem(key, 'value');
9  expect(hasLocalStorageKey(key)).toBe(true);
10});
11
12test('returns false if key does not exist in localStorage', () => {
13  expect(hasLocalStorageKey('missingKey')).toBe(false);
14});
15
16test('returns true for existing key with null string value', () => {
17  localStorage.setItem(key, 'null');
18  expect(hasLocalStorageKey(key)).toBe(true);
19});
20
21test('returns true for existing key with empty string value', () => {
22  localStorage.setItem(key, '');
23  expect(hasLocalStorageKey(key)).toBe(true);
24});

Common Use Cases

  • Feature Initialization Guards

    Determine whether user-specific settings or app state need to be initialized.

  • Safe Retrieval of Stored Data

    Check if data exists before calling loadFromLocalStorage to avoid fallback logic or exceptions.

  • Debugging and Inspection

    Programmatically inspect if certain app state keys were written during a session.

  • Conditional UI Rendering

    Show or hide UI elements (e.g. onboarding modals or notifications) based on presence of flags in localStorage.

Codebase: Utilities -> Storage -> hasLocalStorageKey | Yevhen Klymentiev