venus – 15-09 Dec 10

Can i write this condition in shorter version? I want to get last index of array arr and if the array is emty, I want to get 0 (so basically add -1 to arr.length if arr.length is not 0)
const index = !!arr.length ? arr.length - 1 : 0;
const index = !!arr.length ? arr.length - 1 : 0;
S
ScriptyChris495d ago
Probably like this
const index = arr.length ? arr.at(-1) : 0;
const index = arr.length ? arr.at(-1) : 0;
(or maybe with binary shift magic 🤔 ) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT
UU
Unknown User495d ago