LoginSignup
2

More than 5 years have passed since last update.

localStorage.setItemにundefined, nullを渡すと、getItemで文字列になって死ぬ

Last updated at Posted at 2018-02-14

死にます。

localStorage.setItem("name", undefined)
const name = localStorage.getItem("name")
if (name === undefined) {
  console.log('name is undefined')
} else if (name == 'undefined') {
  console.log('name is undefined string')
}

結果

name is undefined string

guttari256.png

nullも同様。そもそもsetItemの引数は文字列であるべきです。エラーではじくわけでもなく、勝手に文字列になってしまうのが問題。

null, undefinedの場合は、setItemしないようにチェックすること。場合によってはremoveItemで消す必要があるかもしれない。そうするとgetItemでnullを返します。

function setName(value) {
  if (name) {
    localStorage.setItem("name", value)  
  } else {
    // undefined, null, 空文字列のときはここに来る
    localStorage.removeItem("name")
  }
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2