0

I had a problem while destructuring the result of an String.split() operation.

Situation

This code is present in my index.html page in a <script> tag, but I tested it with a separate file, and it has the same behaviour

var timestamp = "2023/06/07T15:50:15.655000";
[timestamp_date, timestamp_time] = timestamp.split("T");
console.log(timestamp_date, timestamp_time);

(I also noticed that the code snippet of stackoverflow doesn't throw an error, but isn't printing the result either)

I used Firefox 68.2 and Edge 112.0, and both throws a ReferenceError, saying timestamp_date isn't defined, which I understand, because timestamp_date and timestamp_time are not defined with a var, const or let.

However, when i try to do it in the console, it works just fine.

Also, when I try with a simpler code, it works perfectly without having to define the variables (It works in the console, but also in a <script> tag)

[a,b] = ["1","2"]
console.log(a,b);

So my question is : Is it a problem with destructuring and String.split(), or am i missing something ?

EDIT

I know that adding const, let or var before the destructuring works, i just want to know why the second case works without

Antonin L
  • 1
  • 1
  • Possible duplicate of https://stackoverflow.com/questions/27386234/object-destructuring-without-var-let-or-const – gilbert-v Jun 13 '23 at 14:14
  • Arrays don't have a `.split()` method. Perhaps you mean `string.split()`? – slebetman Jun 13 '23 at 14:18
  • 1
    Can you clarify when exactly you are seeing the `ReferenceError`? Are you saying that if you have a ` – romellem Jun 13 '23 at 14:21
  • @slebetman Thank you for noticing, I edited it, I was in fact refering to String.split() – Antonin L Jun 13 '23 at 14:21
  • @romellem Exaclty, when the source code of the second snippet is in a script tag, it does work, i do not see a reference error – Antonin L Jun 13 '23 at 14:23

1 Answers1

1

This might help

....
const [timestamp_date, timestamp_time] = timestamp.split("T");
....
Nooruddin Lakhani
  • 7,507
  • 2
  • 19
  • 39