Enzoenzo
Enzoenzo

Reputation: 67

What is the reason JSON.parse() acts differently?

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

Answers (1)

CertainPerformance
CertainPerformance

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

Related Questions