In JavaScript, how to test if localStorage is defined?

In JavaScript, you can test if localStorage is defined or supported by the browser using the following code:

if (typeof(Storage) !== "undefined") {
  // Local storage is supported
} else {
  // Local storage is not supported

This code checks if the Storage object is defined. If it is, then local storage is supported by the browser. If it's not, then local storage is not supported.

To check if a variable or key is defined in local storage, check this question.