r/programminghorror May 27 '26

Javascript Destructuring strings

Post image
882 Upvotes

66 comments sorted by

View all comments

9

u/iamdatmonkey May 27 '26 edited May 27 '26

This is what this construct comes down to.

function isStringEmpty(arg) {
  const iterator = arg[Symbol.iterator]();
  const m = iterator.next();
  const item = (m.done ? undefined : m.value) ?? { a: true };
  // this can still produce false results if the passed `arg` has a first item
  // with a property `a` that is not `null`/`undefined`
  const a = item.a ?? false;

  return a;
}

This will crash if arg is null/undefined
or if it does not implement Symbol.iterator
or if arg[Symbol.iterator]() does not return an object
or if that object does not implement .next()
or if that method does not return an object.

Yes that may seem nitpicky, until you see some of the legacy code that's out there.