Here's an interesting problem I faced when trying a "shortcut" through date manipulation and end up in the dark forest of undefined type errors.
I'll let the code do the talking.
// The set up
let date = new Date()
let isoDate = date.toISOString()
Eg 1: This fails with Uncaught TypeError: Cannot read property 'split' of undefined
let dArray, tArray, YYYY, MM, DD, hh, mm, ss
[dArray, tArray] = isoDate.split('T')
[YYYY, MM, DD] = dArray.split('-') // << ERROR
[hh, mm, ss] = tArray.split(':')
Eg 2: This fails with Uncaught TypeError: (intermediate value)isoDate.split(...) is not a function
let dArray, tArray, YYYY, MM, DD, hh, mm, ss
([dArray, tArray] = isoDate.split('T')) // << ERROR
([YYYY, MM, DD] = dArray.split('-'))
([hh, mm, ss] = tArray.split(':'))
Eg 3: This fails with Uncaught TypeError: Cannot set property 'undefined' of undefined
AND prints the correct value of dArray
.
let dArray, tArray, YYYY, MM, DD, hh, mm, ss
console.log(dArray) // << ERROR
[dArray, tArray] = isoDate.split('T')
[YYYY, MM, DD] = dArray.split('-')
[hh, mm, ss] = tArray.split(':')
Eg 4: And this works fine.
let [dArray, tArray] = isoDate.split('T')
let [YYYY, MM, DD] = dArray.split('-')
let [hh, mm, ss] = tArray.split(':')
SO... can anyone explain why? The MDN docs show array destructuring assignments pre-declared before the assignment. There's even a fun little quiz on the topic. Furthermore, when I type out the commands in the Chrome developer console, there are no errors in Eg 1, 3 and 4. But running inside client application code the browser, all fail except Eg 4.
This little snippet is part of a bigger utils package for quickly switching between ISODate strings and ms since epoch for custom date fields in a fintech order system.
It's a very curious error. I'll wager there's an explanation, and I'd like to know more about it from someone.