0

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.

4Z4T4R
  • 1,954
  • 1
  • 23
  • 39
  • 2
    **Always** use semicolons, don't rely on Automatic Semicolon Insertion unless you're an expert and know how to avoid its pitfalls, or unless you use a linter, otherwise you will occasionally run into bugs like these – CertainPerformance Dec 08 '20 at 22:00
  • Oh, so the issue is the declaration with all the variables bleeds into the next line starting with dArray... never thunk it would be so. Seems I'm more of an expert now. :P – 4Z4T4R Dec 09 '20 at 01:16
  • 1
    Eg `[dArray, tArray] = isoDate.split('T') [YYYY, MM, DD] = dArray.split('-')` since there's no semicolon following the `('T')`, the interpreter sees: `[dArray, tArray] = isoDate.split('T')[YYYY, MM, DD] = dArray.split('-')` as a single statement. It evaluates the right side first: `isoDate.split('T')[YYYY, MM, DD] = dArray.split('-')` which throws since `dArray` isn't defined. – CertainPerformance Dec 09 '20 at 01:19
  • Thats the explanation I was seeking... and I'm even more an expert thanks to you. – 4Z4T4R Dec 09 '20 at 04:41

0 Answers0