-1
var x = JSON.parse(localStorage.getItem('x')).length || 0;

Above code has an error. the || doesn't work in this case I wonder why. Actually I can do this with

var x = JSON.parse(localStorage.getItem('x');
if(x.length){
    x = JSON.parse(localStorage.getItem('x').lengt6h
}

but that's 4 lines of code. Is there any way to do it in one line?

rrk
  • 14,861
  • 4
  • 25
  • 41
Thian Kian Phin
  • 841
  • 2
  • 10
  • 23

4 Answers4

1

localStorage.getItem() will return null if the key is not found, and parse may not like that. But an empty Array should be okay.

var x = JSON.parse(localStorage.getItem('x') || '[]').length;

Using JSON.parse on a null value returns null. And calling length on null throws the error.

C14L
  • 10,584
  • 3
  • 29
  • 46
0

This should work. You need to ask if item x of localStorage isn't null before asking the length of it.

var array = [{ 'one': 1, 'two': 2, 'three': 3 }, { 'four': 4, 'five': 5, 'six': 6 }];
localStorage.setItem('x', JSON.stringify(array));
if(localStorage.getItem('x') != null) var x = (JSON.parse(localStorage.getItem('x'))).length;
NiZa
  • 3,506
  • 1
  • 17
  • 27
0

use ternary operator How do you use the ? : (conditional) operator in JavaScript?

 x=JSON.parse(localStorage.getItem('x')).length?JSON.parse(localStorage.getItem('x')).length:0;
Community
  • 1
  • 1
AlmasK89
  • 1,263
  • 7
  • 16
0

Try a shorthand if:

var x = JSON.parse(localStorage.getItem('x')).length != 0 ? JSON.parse(localStorage.getItem('x')).length : 0
Glenn
  • 1