Hacker News new | ask | show | jobs
by angelmm 1362 days ago
Now I'm worried of using IDs and finding issues with globals in JavaScript. Seems to be a curious issue to be debugged.
3 comments

Avoid globals at all costs - use IIFE [1] instead, wrapping your function in parenthesis and invoking it right away.

[1] https://developer.mozilla.org/en-US/docs/Glossary/IIFE

If you have access to `let`, you can just put `let` declarations into a block. No need for a function to establish scope.
When, today, does it make more sense to organize things around IIFEs and not ES6 modules?
It's 2022, you can use ES2015 modules now. We can leave IIFE to the dustbin of the past.
And then get coworkers to remove it because they don’t understand that you can create scopes like that

    {
        let foo = 1
    };
    // foo is undefined here
If you read the article and the spec, you'll see that any explicitly created variables will always take precedence over automatic IDs, so any globals will always override these IDs.
In the additional considerations section [1], they mention about not consistent behaviors between browsers. Those are the kind of issues that are quite difficult to debug.

[1] https://css-tricks.com/named-element-ids-can-be-referenced-a...

And that could be the problem if you try to access an element by id but a variable has the same name. This renders this option pretty useless.
You shouldn't be using IDs anyways. They are just bad for a lot of reasons. You can only have one on a page and it reduces your reusability. Use classes instead.
ID's aren't bad, they're unique identifiers, and useful for (deep) linking to specific pieces of content within documents. Please use ID's as liberally as you please, and use them for their proper use.
Use ids when JS needs to reference unique elements. Use classes for styling and accessing groups.
JS can do just as well with unique classnames, which avoids issues with ids like those given in the article.
I always presumed this would usually entail a performance hit, since you are accessing something that is not defined as unique.
It's an infinitesimal performance decrease, and it avoids a lot of other issues.