Search code examples
javascriptpushternary

need reference for documentation on ternary operator using push


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


Solution

  • 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().