-1

I have a localStorage value, which I am getting

const marks = JSON.parse(localstorage.getItem('mark'))

Now I am trying to make it robust so that if there is no key with mark in localStorage then it should not break.

localstorage.getItem('mark') ? JSON.parse(localstorage.getItem('mark')) : []
 

So is there any another way through which I can do the null check ?

ganesh kaspate
  • 1
  • 9
  • 41
  • 88
  • 5
    Does this answer your question? [How to check whether a Storage item is set?](https://stackoverflow.com/questions/3262605/how-to-check-whether-a-storage-item-is-set) – angel.bonev Oct 26 '20 at 12:24
  • 1
    Or maybe this question: [Specify default value for HTML5 Local Storage item?](https://stackoverflow.com/questions/13791569/specify-default-value-for-html5-local-storage-item). – norbitrial Oct 26 '20 at 12:25
  • What is wrong with the code you have provided? What characteristics does it lack that you're looking for? As is, your question is too broad for Stack Overflow. – user229044 Oct 26 '20 at 13:00

1 Answers1

0

try:

localstorage.getItem('mark') === null ? [] : JSON.parse(localstorage.getItem('mark'))

EDIT

Of course, It means:

if(localstorage.getItem('mark') === null){
 return '[]'
}else {
JSON.parse(localstorage.getItem('mark'))
}

If item named mark is not null it will parse to JSON and u will get the result

olscode
  • 603
  • 1
  • 5
  • 16
  • Although this answer addresses the question, I would improve a lot if you could edit it and add an explanation on how that code helps – Cleptus Oct 26 '20 at 13:34
  • already edited, I hope the explanation can help you, is like you could either return null or an empty array – olscode Oct 26 '20 at 13:43
  • Your answer got listed in the low-quality review queue, I was suggesting how it could be improved ;-) – Cleptus Oct 26 '20 at 13:44