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'); ...