1

I have the following:

let currentLocalStorage = [];
currentLocalStorage = (initialLoad) ? JSON.parse(localStorage.getItem('tasks')): (currentLocalStorage.push(taskInput.value),currentLocalStorage)

which works but I would like to get a reference or documentation for the following:

: (currentLocalStorage.push(taskInput.value),currentLocalStorage)

so basically we are pushing on to the array and then defaulting to the array. I was surprised that we can do this and was wondering where one we look for the documentation

DCR
  • 10,658
  • 7
  • 38
  • 86
  • 1
    No it doesn't, it only seems like it works. `JSON.parse` will throw instead of fail when it's given bad data, so: never put it in a ternary, just write normal code. Especially given the silliness in the second part of the ternary. The language permits this, but don't write code like this. – Mike 'Pomax' Kamermans Apr 15 '21 at 22:38
  • 1
    Case of a confusing one liner that is actually longer than writing it out with a simpler to read if() :: `let currentLocalStorage = JSON.parse(localStorage.getItem('tasks') || '[]'); if ( initialLoad ) { currentLocalStorage.push(taskInput.value) }` – charlietfl Apr 15 '21 at 23:00

1 Answers1

1

This is using the comma operator. Because .push() returns the new length of the array, you want to make sure you don't assign that to currentLocalStorage, so you use the comma operator to have that expression evaluate to currentLocalStorage.

So it effectively becomes currentLocalStorage = currentLocalStorage in that case, except now the array has one more item thanks to .push().

GregL
  • 32,302
  • 7
  • 58
  • 64