Reputation: 67
I can not determine the difference between these two approaches:
let gigi;
if(localStorage.getItem('gigi')){
gigi = JSON.parse(localStorage.getItem('gigi'))
}else{
gigi=[]
}
console.log(gigi);
While the code above shows empty array, the below one shows up null. Why?
let aa=[]
let che =JSON.parse(localStorage.getItem('aa'))
console.log(che);
Upvotes: 0
Views: 47
Reputation: 370699
getItem
will return the value null
if no value exists at that key in storage.
In the first code, this branch:
if(localStorage.getItem('gigi')){
excludes that possibility. In the second code, you're not doing any such test, you're passing it into JSON.parse
regardless. JSON.parse(null)
will coerce the null
into a string, and will then parse 'null'
into the value null
.
If you want to do this concisely, you can do
const gigi = JSON.parse(localStorage.getItem('aa') ?? '[]')
Upvotes: 2