I remember doing this 25 years ago, but I assume (and hope) it's a huge minority who do this today?
https://github.com/ClickHouse/ClickHouse/blob/master/program...
I'm not sure if I read that that specific experiment was debunked or not, but it certainly sounds familiar to how some developer trends get propagated even though the ground truth as changed.
let table = [
['one','two','three'],
['four','five','six']
];
let b = document.body;
let t = document.createElement('table');
b.appendChild(t);
table.forEach((row,ri) => {
let r = t.insertRow(ri);
row.forEach((l,i) => {
let c = r.insertCell(i);
c.innerText = l;
})
});
Use full words for variable names!As someone who likes to program in Haskell, I feel this pain very strongly. :)
```python
bar = [foo(e) for e in elements]
```
or, using `x`, `n`, `s` and similar when they represent just that, a generic variable with a number, string, etc. I think there is a Code Complete chapter about it.I like to joke, "you think programmers are bad at naming thing, you should see the mathematicians, programmers are infants before the infernal naming sense of the common mathematician".
const te = document.createElement('table');
document.body.appendChild(te);
[
['one', 'two', 'three'],
['four', 'five', 'six' ],
].forEach((r, i) => {
const re = te.insertRow(i);
r.forEach((c, j) => {
re.insertCell(j).innerText = c;
})
});
My personal stance on short variable names is that they are fine as long as their scope is very limited, which is the case here. Rather, the "crime" to me is an overuse of rather pointless variables as the majority of them were only used once.Disclaimer: I have not tested the code and I only write JavaScript once every few years and when I do I am unhappy about it.
As for variables, I (again personally) find it taxing to have many variables in scope, so I do net see their presence as a universal good. If we instead simply use expressions, then there is no need to concern yourself with whether the variable will come into play later on. Thus, I think it increases clarity and favour that over the ease of future modification argument you propose (heck, I would argue that you get better diffs even if you force the variable declaration into a future modification).
As for bikeshedding this piece of code further, if I steal some ideas from chrismorgan [1] and embedding-shape [2] who appear to be way more seasoned JavaScript programmers than me:
const $t = document.createElement('table');
for (const r of
[
['one', 'two', 'three'],
['four', 'five', 'six' ],
]) {
const $r = $t.insertRow();
for (const e of r)
$r.insertCell().innerText = e;
};
document.body.append($t);
This is now rather minimal and the logic is easy (for me) to follow as the scopes are minimal and namespace uncluttered. It was a rather fun little exercise for a language I am not overly familiar with and I learned a few tricks and perspectives. > document.createElement("table").rows[Symbol.iterator]()
// Array Iterator { constructor: Iterator() }
HTMLTableElement.prototype.rows actually just returns a HTMLCollection, so same as document.forms, or document.getElementsByClassName. HTMLCollection implements Symbol.iterator as you would expect.https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableEl...
It's a brain scramble because you can't just read in toto.
Well, you can literally, but, you don't feel like you grok it.
And when you take a second pass you gotta slow down and stop and parse "what's r here? is it relevant? oh rows?"
It's one of those things that's hard to describe because it doesn't sound like much if you got it. And this example is trivial, especially if you're not open to the idea its a problem (r/c = rows/columns) But it's nigh-impenetrable in other scenarios.
You feel like you're barely understanding something that you actually might grok completely.
I agree, it's highly context-specific.
In a small demo for a small blog post with basically no complexity? Go ahead, use 1 character variable names, it really isn't difficult.
In the 1000 long CUDA kernel where you barely understand what's going on even though you understand the concepts? I'd be favoring longer descriptive names than one letter names for sure.
It's a small critique, I'm sorry it got upvoted by other people.
It takes time for the contrarian dynamic to work itself out (https://hn.algolia.com/?dateRange=all&page=0&prefix=true&que...), and once that happens, the original problem subsides but and the secondary problem (shallow objection to the objection) sticks out like a sore thumb.
It's usually enough to downvote (or, in egregious cases) flag a post that shouldn't be at the top. In really egregious cases, emailing hn@ycombinator.com is also a fine idea.
From the guidelines: "Please don't sneer, including at the rest of the community." - https://news.ycombinator.com/newsguidelines.html
In just 4 lines you have r, row, t, ri, l, i and c.
The full variables names are so short anyway that personally I'd write them out. Code does evolve and there's a risk of this suffering as a result.
RowIndexFactoryGeneratorService rowIndexFactoryGeneratorService = new RowIndexFactoryGeneratorService();
RowIndexFactory rowIndexFactory = rowIndexFactoryGeneratorService.getTheFactoryOrSomethingIDontCare();
RowIndex rowIndex = rowIndexFactoryGeneratorService.generateRowIndex();If you're going to use short names at least make it clear which belong together. Especially don't use different lengths when things ought to be similar.
data.forEach((row,i) => row.forEach((ele,j) => ... ))that's like saying in spoken language "don't ever use pronouns, or even first or nicknames, use full given names"
This one hurts the most. Save a few bytes for an ungodly amount of mental friction.
let table = [
['one','two','three'],
['four','five','six']
];
let $body = document.body;
let $table = document.createElement('table');
$body.appendChild($table);
Always felt it worked out short and sweet, and as long as you're not refactoring a jQuery codebase, seems to work out well in practice.Not sure when it was (10-15 years ago), but at some point everything became <div>s. So, instead of semantic markup, HTML became a UI toolbox.
It’d be interesting to have a parallel DocBook web for technical content, where consumers of that content could apply their own styles to render it in a way that’s best for them.
(I’m not saying I like the world we live in, but I don’t see a likely alternative.)
These days it's a moot point anyway, because everyone is using things like tailwind which provide a full reset for things like default buttons, so there really is no excuse.
I think semantic HTML is a great idea but it's kind of jaded to expect it at this point.
It also doesn't help that semantic elements have styling. That right there gives people good reason to use a neutral container as a baseline. In fact I would go as far as to say that having both div and span is a bad design decision. They are just aliases for css `display` values.
Just look at how they salivate for WASM where everything is closed up and inaccessible, including a11y.
I was replying to the wrong comment, because I was responding to this:
> I still use this pretty much everywhere to create HTML tables. Do people use something else now?
Regarding React: what would be the benefit for using this old syntax sugar in its vDOM implementation?
Page reflow is not an issue for vDOM as it batches such updates anyway?
And using syntax sugar without benefits in the DOM reconciliation would be pointless.
React also doesn't locate form input elements using document.forms.[name]?.[name] because... why should they?
Just because they can...
Regarding the creation of tables, the most common way to do it would be... parsing initial document's HTML?!
Seems to me that we have redundant mechanisms for specifying semantics: tags and attributes (and classes as a specific attribute). Seems to me that tags are really just syntactic sugar for things like roles. Tables in particular are easily abused.
Of course I use the tag names, because they're idiomatic. But I feel like a newbie who identifies divs as the only true structure builder has a proper developer's intuition for separating presentation from content.
As long as you think about semantics and accessibility and does the extra work to add those things, then not really.
But why add those extra things when we already get those for free by doing <h1> and then customizing the style? Everything you'd need to manually add, automatically works fine then, so seems like a no-brainer to avoid putting more work on your table.
Just use <a> please :)
Best case I'm hoping it's because they were required to get an exact design, but they really should have pushed back on that one if so.
"table" was never deprecated in HTML at all, but was discouraged for general layout (we were aware of this even in the early 2000s). But for representing tabular data - like... data in rows/columns from spreadsheets (with column headers and such)... HTML tables were absolutely the right (only?) way to present this.
I was at that company less than a year...
Aside: I started with Perl CGI scripts, then ColdFusion, and finally Classic ASP back in the 90s. I had a chuckle a couple years ago dealing with a younger developer who was shocked that and oldster like me was up on new-fangled SSR patterns.
If was much simpler to build tables in javascript with this rather than using document.createElement.
Perhaps this was one of those things that you just had to know about, or be working on data heavy web apps.
Tables are great. I don't doubt that CSS stuff is more capable, but the old ones are still useful.
What is discouraged is using tables as invisible layout grids - and that was their primary de-facto usecase before CSS and grid layouts. But that had always been a hack, even though a necessary one.
After too.
I've seen enough "Introduction to CSS"s filled with caveats and hemming & hawing to know that it's all to be avoided when+if possible. I know, I know, there's a whole wide wonderful world out there full of aligns and borders and containers and insets and margins and masks and offsets and paddings and positions oh my. Bleccch..
Hack implies brittleness. Using tables for layout was just fine for all but the most ideologically pure pedants.
Doing table-free multi-column layouts involved doing crazy “float: left/right + padding + margin” with an heavy sprinkle of IE6 clearfix hacks to work right. I mean eventually people dialed in the correct incantations to make table-free designs work for IE6 but it was never quite as straightforward or reliable as a good old fashioned table. Many megajoules of energy were wasted on webform drama between the pragmatic "fuck you, tables just work and I have shit to ship" webdev and the more academic "tables break the semantic web and aren't needed, use CSS." crew.
Like most things, the "tables are evil" mantra was taken too far and people started to use floated divs (or <li/>’s or <span/>’s or whatever) for shit that actually was tablular data! (I was guilty of this!).
And like most things, a lot of the drama went away when IE6 finally went away. People who weren't around back then simply cannot understand exactly how much IE6 held back modern web design. You could almost count on half your time being spent making shit work for IE6, despite the ever decreasing amount of traffic it got. I'm pretty sure I almost cried the day Google slapped a "IE6 will no longer be supported" on it's site.... the second they did that, my site got the exact same banner. Fuck IE6. The amount of costs that absolute pile of shit browser caused the industry exceeded the GDP of entire nations.
Anyway.... back to adding weird activex shit in my CSS so IE6 can support alpha-blended PNGs....
According to who?
https://github.com/WebKit/WebKit/blob/28fa568972a4d34d867948...
Thanks Vercel & Meta for protecting us.
Huh? Why'd you involve state in this or any imperative code? You render the rows/columns as you'd render any other DOM elements in React, pass in the data as props and iterate on it, create children and pass them to render.
The idea of the author seems to be that this part of the DOM API that could benefit from backwards-compatible additions. So, by "abandoned", he hints at the headroom for building more table capabilities into the platform.
He compares it loosely to the form element API and the additions it received over the last decades.
In the case of tables, I could think of things such as a sorting, filtering API, but I can't tell whether that's what he means.
Even if, for some reason, you were filling in the table content dynamically via jQuery, I think the fashion there was also to just pass in whole HTML markup snippets as strings to be injected into the DOM, so you'd also more likely use plain <tr> elements than this table-specific API, same as with a 'hype' framework of now.
That's nice, but isn't that what the standard DOM methods are already doing? Or does that API have any additional abilities?
Nevertheless, that's really cool and potentially saves a lot of tedious and error-prone DOM navigation.
Topic is reminiscent of a submission from yesterday about XSLT:
I doubt that's true for .insertCell() and .insertRow().
I fear this will be even worse now that we have the origin File System API and people can bring their own database engines (like web-assambled SQLite). But for those of us that are striving towards smaller download sizes this is a disaster.
Not quite sure what the author means by that. Re-rendering pnly happens when the current task queue elemt has been processed. Never while JS is running (aside from webworker and the like). I would honestly be surprised if this API had much (if any) performance benefits over createElement.
And there is way more to it.
This kind of code was common and also the starting point of every modern language innovation we have today in JavaScript - even TypeScript, and maybe any modern web development on the server as well.
Tables were the only way to create browser independent layouts dynamically. Or put another way: adding interactivity to websites. And simply because hacking is fun and browsers were experimenting with APIs accessible by JavaScript.
CSS was still bleeding from ACID tests, Netscape was forgotten, Mozilla build Phoenix out of the ashes of the bursting bubble and called their effort Firefox.
In Germany there was and still is the infamous selfHTML project. I remember vividly reading and testing Stefans Münz tutorials on this topic. The content is untouched, only the layout changed, so go back in time for more table fun:
https://wiki.selfhtml.org/wiki/Beispiel:JS-Anwendung-Tabelle...
https://wiki.selfhtml.org/wiki/JavaScript/Tutorials/Tabellen...
It was pretty common to have large one file websites: php and html with css and javascript mixed.
There was no git, no VisualStudio Code, Claude Sonnet - no, Notepad and later Notepad++
(Even the DOOM guys had no version control system in the early stages.)
For me John Resig shines out here. Epic genius behind jQuery. The source code was pure magic, and his book "Secrets of the JavaScript Ninja" is for me the all time climax in programming excellence.
If you never utilised the prototype property, you will never understand any of the most basic structures and inner workings JavaScript has to this day and why Classes are "syntactical sugar" for functions and nothing else.
Function.toString in combination with New Function made me enter 10 matrices in parallel at the time. What a revelation. :D
Nicholas Zakas comes close with his seminal Web Development book, in which he featured every Browser API available at the time with examples on roughly 1000 pages. To this day, exercising most of it and understanding the DOM and Windows object was the best investment ever, because and this fact 15 years later paved the way for the success of a financial SaaS platform. Lost wisdom, not covered by any modern framework like Angular or ReacJS.
It’s not about the <table> element itself—we hope everyone knows about tables—but rather about the table-specific DOM interface, including things like HTMLTableElement.prototype.insertRow() and HTMLTableRowElement.prototype.insertCell() as alternatives to the generic DOM techniques like Document.prototype.createElement() and Node.prototype.appendChild().
These are handy if you’re hand-writing your DOM interactions, but libraries that construct and maintain DOM trees (e.g. React, Svelte, Vue) will never use them, and that’s the direction everything has headed, so in practice they’ve fallen into near-complete disuse.
They match HTML syntax in another important way: HTML tables have thead/tbody/tfoot section elements, but you can mostly skip writing them in HTML syntax because it’ll imply <tbody> open and close tags. Likewise in this interface, if you have a thead/tbody/tfoot element you can call .insertRow() on it, but you can also call .insertRow() on the table, and it’ll put it in the last tbody, creating one if necessary. Meanwhile, I presume in React/Svelte/Vue/whatever you must write out your tbody manually.
I’ve definitely used at least .insertRow, .insertCell, .createTHead, .rows and .cells in the last five years in no-library throwaway/demo scripts where I was generating tables.
—⁂—
Concerning the specific example given, here’s what I find a clearer code style, using for instead of forEach, using better variable names, and omitting the index argument to insertRow/insertCell which was quite unnecessary and only confused matters (the author doesn’t seem to have realised it’s optional):
let data = [
['one','two','three'],
['four','five','six']
];
let table = document.createElement('table');
for (const row of data) {
let tr = table.insertRow();
for (const value of row) {
tr.insertCell().innerText = value;
}
}
document.body.append(table);I still remember reading a news article on C|net about the addition of the <table> element.
Yeah, I'm old.
dtagames•15h ago
begoon•15h ago
the__alchemist•15h ago
zetanor•15h ago
SahAssar•15h ago
loloquwowndueo•15h ago
cogman10•15h ago
Young folk don't understand just how wildly different IE5 was to the Netscape or the Mozilla browser. Or just how bad Javascript was when it started to be used on the internet.
I've lived through and seen the evolution. For all the shit the JS community takes for constantly revving frameworks, it's 1000x easier to make a website that looks the same regardless of browser due to a lot of these frameworks and browsers themselves evolving.
dvratil•14h ago
embedding-shape•15h ago
<table> just gives you so many good defaults (semantic structure, accessibility, column styling, column alignment, keyboard navigation) for free compared to using CSS to create your own table, that I'm not sure why you wouldn't use <table> for tabular data.
Of course, if you need masonry, card grids and so on it makes sense, do actual layouting with layouting tools. But thankfully <table> hasn't died just yet, it's still better than CSS for many use cases.
dtagames•10h ago
andai•15h ago
pikuseru•15h ago
theandrewbailey•14h ago
dtagames•9h ago
theandrewbailey•8h ago
Compare https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/...
with https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_la...
joquarky•5h ago
nophunphil•13h ago
Tables built with flex and grid absolutely can be made accessible with WAI-ARIA, but native table elements are harder to mess up.