I know this is not strictly JS at all :)
However I use this technique in several projects, always copy pasting a gist at GitHub.
Thought I'd publish and share it, as it's really useful.
Also, feel free to use @loopmode/events for this. It will use only a single DOM event listener no patter how many components use your hook! (Shameless self-advertising here, I wrote it, but it's a perfect use case)
I'm still in the "meh" phase, even after months of working on some projects that use typescript as well.
I do see the benefits, no question, but I'm still not 100% convinced. It might be more pleasant to write, but it's terribly noisy to read.
It does encourage writing more performant code tho. The stricter you type, the better your resulting JS can be optimized by e.g. V8.
You can write performant JS manually too, but it takes a lot of experience and discipline.
Just recently I migrated a library of mine to TS where the very complicated typing basically rubbed in my face that my JS was simply bad. It was about a flags object in the concrete case, and usually it had string keys and boolean values, but in some cases it could have string values for certain keys. After struggling a lot to properly type all modules and functions that consuming that object, I gave up, accepted that my approach was shite, and rewrote the architecture to use monomorphic objects instead, introducing a new and separate logic that deals with the string case. Now stuff is much cleaner, overall and if it were to scale, it would surely even perform better.
Still, I'm not 100% convinced yet. You read a lot that you don't have to type everything, and you can just add TS on top of js because it's a superset blah blah. In my experience, that's not realistic, and going Typescript does take away the expressivity of Javascript (one of its best features).
Let's see. Hated Javascript for years, now I love it :)
"There you have it. If you just wanted a sticky header and didn't need to know what the section you are currently looking at you could have simply added just the position: sticky. The ability to click buttons to scroll to sections, and highlight the section the user is in provides a nicer experience." :)
Don't understand the downvote.
Keep in mind that there is still an ongoing discussion on whether in certain cases a missing value should be resolved to undefined, as it is now, or to null, as some demand.
In any case: e.g. `foo?.bar || 'foo'` will always work, but avoid `if (foo?.bar === undefined)`