venus
venusβ€’2y ago

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;
2 Replies
ScriptyChris
ScriptyChrisβ€’2y 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
reactibot
reactibotβ€’2y ago
This thread hasn’t had any activity in 12 hours, so it’s now locked. Threads are closed automatically after 12 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/1051153652888371200