localStorage.getItem('key') versus localStorage.key versus localStorage['key']

All three, localStorage.getItem('key'), localStorage.key, and localStorage['key'] methods, do the same thing. However, it is advisable to use the provided methods for the following reasons:

  • localStorage.getItem('key-does-not-exist') returns null, whereas localStorage['key-does-not-exist'] will return undefined. In JavaScript, null is not equal to undefined For example, suppose that you want to set a key that is actually the property of an object as well, or as a function name, such as getItem and setItem. In this case, you're better off with the getItem approach, as follows:
    localStorage.setItem('getItem', 'whohoo we are not overwriting getItem'); // #1localStorage.getItem('getItem'); ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.