<andres-carmona />

TIL #11: Symbol.asyncIterator
First published on
on html, javascript

Symbol.asyncIterator

I am re-reading some parts of the JavaScript reference on MDN and came across several JavaScript features that were unknown to me and are very interesting.

In this case, an object with a Symbol.asyncIterator property that is also a generator, and can produce (yield) values that are then consumed in a for await loop. Simply awesome!

const delayedResponses = {
  delays: [500, 1300, 3500],

  wait(delay) {
    return new Promise((resolve) => {
      setTimeout(resolve, delay);
    });
  },

  async *[Symbol.asyncIterator]() {
    for (const delay of this.delays) {
      await this.wait(delay);
      yield `Delayed response for ${delay} milliseconds`;
    }
  },
};

(async () => {
  for await (const response of delayedResponses) {
    console.log(response);
  }
})();

// Expected output: "Delayed response for 500 milliseconds"
// Expected output: "Delayed response for 1300 milliseconds"
// Expected output: "Delayed response for 3500 milliseconds"

TIL #10: Javascript in 2026
First published on
on html, javascript

I was reading this excellent article on Frontend Masters, where some of the new features already available in JavaScript are described, along with others expected later this year. Among them, the ones I want to highlight most are the following:

Iterator.from:

const result = Iterator.from(array)
  .map(x => x * 2)
  .filter(x => x > 10)
  .take(3)
  .toArray(); // No new arrays created, computation stops after 3

Set methods:

const youKnow  = new Set(["JS", "Python", "CSS", "SQL"]);
const jobNeeds  = new Set(["JS", "TypeScript", "Python"]);

// Skills the job wants that you already have
youKnow.intersection(jobNeeds); // -> Set {"JS", "Python"}

// Everything combined - your full stack + job needs
youKnow.union(jobNeeds); // -> Set {"JS", "Python", "CSS", "SQL", "TypeScript"}

// What the job needs that you DON'T know yet (skill gaps)
jobNeeds.difference(youKnow); // -> Set {"TypeScript"}

// Skills you have that the job doesn't care about
youKnow.difference(jobNeeds); // -> Set {"CSS", "SQL"}

// Skills that appear in only one set, not both
youKnow.symmetricDifference(jobNeeds); // -> Set {"CSS", "SQL", "TypeScript"}

// Are all job requirements a subset of what you know?
jobNeeds.isSubsetOf(youKnow); // -> false

// Do you have every skill and more?
youKnow.isSupersetOf(jobNeeds); // -> false

// Do you and the job have zero overlap?
youKnow.isDisjointFrom(jobNeeds); // -> false

Promise.try:

Promise.try(() => loadUser(id))
  .then(user  => render(user))
  .catch(err  => showError(err));

Import attributes: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import/with

import data from "./file.json" with { type: 'json' }

import exampleStyles from "https://example.com/example_styles.css" with { type: "css" };

document.adoptedStyleSheets.push(exampleStyles);

using and await using: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/using

class FileHandle {
  constructor(path) {
    this.path = path;
    console.log(`Opened ${path}`);
  }

  async write(data) {
    // ... write data
  }

  async [Symbol.asyncDispose]() {
    await someFlushOperation();
    console.log(`Flushed and closed ${this.path}`);
  }
}

async function saveData() {
  await using file = new FileHandle("output.txt");
  await file.write("hello world");
  // file is automatically flushed + closed here, even if an error is thrown
}

Array.fromAsync: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromAsync

function createAsyncIter() {
  let i = 0;
  return {
    [Symbol.asyncIterator]() {
      return {
        async next() {
          if (i > 2) return { done: true };
          i++;
          return { value: Promise.resolve(i), done: false };
        },
      };
    },
  };
}

Array.fromAsync(createAsyncIter()).then((array) => console.log(array));

Intl.Collator:

const words = ['äpfel', 'Zebra', 'Bär', 'Apfel', 'über'];
const collator = new Intl.Collator('de');

const sorted = words.sort(collator.compare);
console.log(sorted); // ['Apfel', 'äpfel', 'Bär', 'über', 'Zebra']

TIL #9: ownerDocument.defaultView
First published on
on html, javascript, typescript

Despite considering my self a seasoned programmer and being developing web applications for over 15 years, I’m surprised I didn’t know about the ownerDocument.defaultView property.

I basically returns the window object (or null) associated with a specific DOM node. It could be used to safely attach an event listener to a window object from a component that is rendered outside the main window where the application was initially rendered (think portals).

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("light");
  const ref = useRef(null);

  useEffect(() => {
    const win = ref.current?.ownerDocument.defaultView || window;

    const toggle = (e) => {
      if (e.metaKey && e.key === "d") {
        e.preventDefault();
        setTheme((t) => (t === "dark" ? "light" : "dark"));
      }
    };

    win.addEventListener("keydown", toggle);

    return () => win.removeEventListener("keydown", toggle);
  }, []);

  return (
    <div ref={ref} className={theme}>
      {children}
    </div>
  );
}

From the same article, also learned about useId and cache 😛

Reference: https://shud.in/thoughts/build-bulletproof-react-components, great article btw! 💯


My Game development intro
First published on
on gamedev, games, javascript

Since a long time ago I’ve wanted to start developing a game, and now that my 7 years old kid asked for a game as his next birthday I think is a good time to start. I have no problem learning a new language like Python, C# or Rust, but as a web developer I wanted to start by using my main programming language, Javascript.

So, to start learning (and to get my hands dirty), I want to replicate the game made by Drew Conley Build a Multiplayer Game with JavaScript & Firebase.

More coming soon…