JavaScript Refresher and Detailed Study - Part 13

Last updated on 24 Nov 2026
Post series: Part 1,     Prev Part (12),     Post Series TOC

Contents


Gemini chat and dates

Gemini chat: JavaScript-Refresher-P13-20261112

  • Model: Pro 3.1 Medium which got changed on or slightly before 20 Nov. 2026 to Neon Medium

Dates: 12 to 14 Nov., 17 to 24 Nov. 2026


superposition informal term for combined sum of all properties and methods an object inherits from its entire prototype chain

https://javascript.info/basic-dom-node-properties uses the term 'superposition'. I checked with Gem about it.

Key points from Gem's response:

  • In this context, the author uses "superposition" simply to mean the accumulation or combined sum of all the properties and methods an object inherits from its entire prototype chain.
  • "Superposition" is not a formal term in Object-Oriented Analysis and Design (OOAD)
  • The term is actually borrowed from physics and mathematics, describing the principle where two or more physical states or waves add together to form a single combined state.
  • JavaScript developers do not use "superposition" to describe inheritance or object properties. If you used that term in a pull request, a technical interview, or a GitHub issue, other JS engineers would likely be confused or assume you were talking about quantum computing.
  • The universally understood terms in the JavaScript ecosystem are:
    • Prototype chain (the structural linkage of objects)
    • Prototypal inheritance (the overarching concept)
    • Delegation (how property lookups actually work by deferring to the parent)
    • Object composition or Mixins (when explicitly copying properties from multiple source objects into one, like Object.assign())
  • You can safely file "superposition" away as just a colorful, idiosyncratic metaphor chosen by the javascript.info author.

To get node type, nodeType may be simpler than instanceof

Me: https://javascript.info/basic-dom-node-properties states, "In modern scripts, we can use instanceof and other class-based tests to see the node type, but sometimes nodeType may be simpler." Ur view pl.

Gem: I agree with the author. While instanceof is the modern, idiomatic JavaScript way to verify object types, nodeType remains incredibly practical—and sometimes superior—for low-level DOM traversal.

Given your C++ background, a good mental model is that nodeType is like checking a fast enum flag on a struct, whereas instanceof is closer to checking runtime type information (RTTI) or performing a dynamic_cast up the inheritance tree.

Here is the breakdown of why nodeType holds its ground and when you should reach for each:

The case for nodeType (The Integer Flag)

  • Raw Speed and Simplicity: nodeType returns a primitive integer (1 for Element, 3 for Text, 8 for Comment). Checking if (node.nodeType === 1) is a simple O(1) integer comparison. When you are writing algorithms to recursively parse or traverse thousands of DOM nodes, this is the most efficient check.
  • Cross-Iframe Safety: If your script interacts with DOM nodes inside a different <iframe> or popup window, node instanceof HTMLElement can actually fail and return false. This happens because the iframe has its own global execution context and its own distinct HTMLElement constructor memory reference. node.nodeType === 1, being a primitive integer, is safely portable across execution contexts.
  • The "Whitespace Filter": The most common historical and modern use of nodeType is iterating over element.childNodes and ignoring the invisible Text nodes (spaces and newlines in the HTML).

The case for instanceof (The Prototype Walker)

  • Deep Specificity: nodeType can only tell you a node is an "Element" (1). It cannot tell you what kind of element it is. If you need to know whether an element is an <input> rather than a <div>, you must use node instanceof HTMLInputElement (or check node.tagName).
  • Type Narrowing (TypeScript/JSDoc): If you are writing modern JS in VS Code, using if (node instanceof HTMLInputElement) explicitly tells the IDE's language server to expose input-specific properties like node.value. A nodeType check does not provide this intelligence.

The Pragmatic Verdict Use nodeType === 1 when you are writing a loop to walk the DOM tree and just want to strip out text and comment nodes. Use instanceof when you are handling an event or validating a specific element type before calling its unique methods.

Writing to outerHTML is an anti-pattern in modern JavaScript

Me: 13 Nov. Javascript.info outerHTML: full HTML of the element says, "Beware: unlike innerHTML, writing to outerHTML does not change the element. Instead, it replaces it in the DOM." It goes on to say that it is strange.

I have come across some vanilla JS apps code and, very rarely, IIRC, even ReactJS apps code, accessing/modifying innerHTML but don't recall any case where outerHTML was used.

Gem: Your memory is spot on. Writing to outerHTML is an anti-pattern in modern JavaScript, and you will almost never see it in production codebases, much less in React.

The reason the javascript.info author calls it "strange" comes down to a jarring disconnect between the JavaScript variable reference and the underlying DOM tree state.

Here is what happens under the hood when you write to outerHTML:

  1. The browser's HTML parser reads the new string and creates an entirely new DOM node in memory.
  2. It locates the original element in the live document tree, replaces it with the new node, and detaches the old element.
  3. The trap: Your JavaScript variable still points to the old, detached element.

If you run let myDiv = document.getElementById('my-div'); myDiv.outerHTML = '<p>Replaced</p>'; and then try to attach an event listener to myDiv on the very next line, you are operating on a "ghost" object hovering in memory, completely disconnected from the webpage. Think of it like operating on a stale pointer to an object that was just removed from the active render graph.

Why you won't see it in React: React manages the DOM via a Virtual DOM tree. While React offers dangerouslySetInnerHTML to let you dump raw HTML inside a container node (treating the children as a black box), it strictly forbids replacing the container node itself. If a node replaces itself out-of-band using outerHTML, React loses its anchor to the real DOM. The next time React runs its reconciliation cycle, it will crash because the node it expects to update is missing from the document.

The Modern Vanilla Alternative: When modern vanilla JS developers need to replace an entire node, they use the replaceWith() method instead. It is much cleaner to create a new element and explicitly call oldNode.replaceWith(newNode). It makes the architecture explicit that a destructive replacement is happening, rather than disguising it as a simple property assignment.

You might occasionally see outerHTML used to read a node (e.g., logging an element's full tag and attributes to the console for debugging), but writing to it is best left in the past.

Count descendants: querySelectorAll flattened approach is preferred over recursive traversal

Me: I am looking at solutions to https://javascript.info/basic-dom-node-properties#count-descendants.

First here is my approach where I wanted to get exposure to recursively traversing the list. (In private repo, count-desc-ex-2.html in dom-node-properties folder)

Gem: Your approach in count-desc-ex-2.html successfully isolates the text nodes from the nested elements and perfectly achieves your goal of practicing manual recursive DOM traversal.

You effectively applied the nodeType check we discussed previously. By iterating over the raw childNodes and checking for Node.TEXT_NODE, you surgically extracted the category text (like "Mammals") without accidentally grabbing the text contents of the nested <ul> elements.

From an architectural standpoint, your script implements a hybrid approach:

  1. Manual Depth-First Search: You are manually walking down the tree by recursively calling printUnorderedListElem when you hit a UL.

  2. Native Deep Search: At each UL branch, you call childNode.querySelectorAll('li').length.

While this yields the correct output, it results in redundant work for the browser. querySelectorAll inherently traverses the entire subtree of the node it is called on. Because you are calling a native recursive search from inside your own manual recursive loop, the lower-level nodes are being parsed multiple times.

When you lean fully into the modern DOM API, manual recursion for this specific problem can be entirely bypassed. Because querySelectorAll flattens the tree into a linear NodeList, the canonical solution to this javascript.info exercise relies on a single loop:

---snipped---

This API-driven approach is how you will typically see DOM nodes processed in vanilla JS apps today. However, since your explicit goal was to gain exposure to traversing the list recursively from scratch, your implementation is a solid, working exercise in manipulating the raw childNodes and children properties.

Me: Noted the point about redundant work in my approach. Here's my version of the tutorial suggested solution which seems to be similar to what you gave above (In private repo, file count-desc-ex-3.html in dom-node-properties folder)

Gem: Your implementation in count-desc-ex-3.html elegantly captures the modern, flattened approach to DOM traversal. By leveraging document.body.querySelectorAll('li'), you let the browser's highly optimized C++ engine do the heavy lifting of finding all the descendants at once.

There is one small but important detail to catch in this snippet. Notice these two lines inside your loop: liText = li.firstChild.data.trim(); numNestedListItems = li.querySelectorAll('li').length;

Because they are missing a let or const declaration, JavaScript will quietly attach both liText and numNestedListItems to the global window object.

Coming from stricter languages like C++, JavaScript's historical looseness with variables can be a notorious trap. If you were writing this inside a modern React component or an ES6 module, the build tools (which automatically enforce JavaScript's "use strict" mode) would instantly throw a ReferenceError. When writing standalone vanilla scripts like this one, it is a good habit to drop "use strict"; at the very top of your <script> tag to force the engine to catch these accidental globals.

Other than that scoping detail, the logic is flawless. It correctly extracts the text node and safely counts the nested elements.

Me: Good catch. Fixed it. Also added 'use script'

Noted the point about modern, flattened approach to DOM traversal by leveraging document.body.querySelectorAll('li'). The exercise requirement could be met with the approach. But if one wanted to also show hierarchy in the console log output like in my approach, then querySelectorAll() has the big issue of removing all hierarchy information.

Gem: When preserving depth and parent-child relationships is the requirement, querySelectorAll actively works against you by collapsing the tree structure into a one-dimensional list.

To build an indented, hierarchical console log, the algorithm must track state—specifically, the current depth level—as it moves down the branches. A flattened NodeList drops the edges connecting the nodes, making it difficult to know if a given <li> is a direct child of the root or nested three levels deep without writing messy, reverse-walking DOM logic (like counting node.parentElement hops) for every single item.

Just like walking an n-ary tree in C++, rendering a hierarchy natively requires a recursive or stack-based depth-first search. Your initial manual recursive traversal, passing down a numTabs integer to track the current level, was the exact right architectural choice for generating a visual tree.

This highlights a core reality of DOM manipulation: the native query APIs are highly optimized for fetching nodes quickly, but mapping those nodes to complex, state-aware data structures still requires classic algorithmic traversal.

For std HTML attr, DOM object properties are used instead of getAttribute() ... (with exceptions); For custom attr, data-* is used (<div data-custom-id="123"> ... div.dataset.customId)

Me: 14 Nov. ... https://javascript.info/dom-attributes-and-properties#html-attributes mentions that standard HTML attributes are shown as DOM element object properties but non-standard HTML attributes are not. Instead non-standard HTML attributes have to be accessed using hasAttribute() and getAttribute() methods. Also getAttribute() method works with standard HTML attributes too and so these attribute methods seem to be a definitive way to access attributes of HTML elements (standard and non-standard). Any idea why we have this different treatment of non-standard attributes for DOM element object properties? Also, in modern vanilla JS apps, what way is preferred for accessing/modifying element attributes in JS code?

Gem: The division between standard properties and getAttribute() stems directly from how the browser's underlying engine (written in C++ or Rust) maps the document tree to JavaScript objects.

Standard attributes are mapped to predefined members on the C++ HTMLElement classes and exposed via WebIDL bindings. When the engine parses a standard attribute like id or type, it knows exactly which memory slot to populate. Non-standard attributes, however, are completely arbitrary.

If the browser automatically created a live JavaScript property for every random HTML attribute it encountered, it would risk catastrophic naming collisions. Imagine an HTML tag written as <form submit="true" appendChild="yes">. If the DOM engine blindly mapped those arbitrary attributes to JavaScript properties, it would instantly overwrite the native form.submit() and form.appendChild() methods, breaking the page. To prevent this, arbitrary HTML strings are quarantined in an internal dictionary, accessible safely via getAttribute().

The Modern Vanilla JS Preference

In modern vanilla JS, the standard practice is to use DOM object properties whenever possible and strictly avoid getAttribute() / setAttribute() unless you have a specific edge case.

Here is why DOM properties are preferred:

  • Live State vs. Initial State: This is the biggest trap for developers. If you have <input type="text" value="Hello"> and the user types "World" into the box:

  • input.value (Property) returns "World" (the live, current state).

  • input.getAttribute('value') (Attribute) returns "Hello" (the original string parsed from the HTML).

  • Type Casting: DOM properties automatically cast to their appropriate types.

  • checkbox.checked returns a boolean (true/false).

  • checkbox.getAttribute('checked') returns an empty string "" (if present) or null (if absent), forcing you to write clunky existence checks.

  • Performance: Accessing a direct property on an object is generally faster than invoking a method that searches an internal attribute dictionary.

Handling Custom Attributes

For non-standard attributes, modern developers do not use random HTML strings. They use the HTML5 data-* specification, which provides a dedicated, safe namespace for custom data.

Instead of writing <div custom-id="123"> and using getAttribute('custom-id'), you write <div data-custom-id="123">. The browser then automatically bundles this into a dedicated DOM property called dataset. You access it in JavaScript simply as div.dataset.customId.

When getAttribute() is Actually Required

You only reach for the attribute methods in a few specific scenarios:

  1. Reading relative URLs: anchor.href will always return the fully resolved absolute URL (e.g., [https://example.com/page.html](https://example.com/page.html)). If you specifically need the literal relative string written in the HTML (/page.html), you must use anchor.getAttribute('href').
  2. SVG Manipulation: SVG elements have a notoriously complex DOM mapping. For SVGs, setAttribute() is often required to reliably update visual properties.
  3. ARIA attributes (Legacy): While modern browsers support properties like element.ariaExpanded, working with older codebases often requires setAttribute('aria-expanded', 'true').

DOM properties often provide processed/computed value while attributes show HTML source code values; E.g. href property is always full URL whereas href attribute gives href as in HTML

(This section is slightly later on in chat.)

Me: As per https://javascript.info/dom-attributes-and-properties#dom-properties-are-typed, href DOM property is always the full URL. getAttribute is useful to get the href as written in the HTML. Is that correct? (In DevTools console, I confirmed that it is the case.)

Gem: Yes, that is exactly correct. This is one of the most practical and common reasons to reach for getAttribute() in modern JavaScript.

When you parse an element like <a href="/contact.html">Contact</a>:

  • The property anchor.href evaluates the context and returns the fully resolved absolute URL (e.g., [https://example.com/contact.html](https://example.com/contact.html)).
  • The method anchor.getAttribute('href') returns the exact literal string parsed from the HTML document (/contact.html).

This serves as a perfect example of how DOM properties often provide a processed or computed value, while attributes act as a faithful record of the raw HTML source code.

id-named 'global' variables are convenient for DevTools console debugging and exploration but should not be used in production apps

(This section is slightly earlier on in chat.)

Me: While I clearly understand the danger of using id-named 'global' variables in JS apps, I find that for DevTools console debugging and exploration, it is a convenient shorthand. If I want to check the the DOM object for a div with id of div1, I simply have to type div1 in DevTools console. div1.style shows me the style object for it. That's convenient.

(Related section: Avoid using dangerous feature of browser doing on-demand search for HTML element with id attribute matching undeclared variable name in JS script code (id-named 'global' variable).)

Gem: You are completely right—exploiting id globals in the DevTools console is a standard, highly effective debugging shortcut used by almost all frontend developers.

While relying on them in a production script is a namespace collision nightmare, the console is an ephemeral sandbox. Browser vendors specifically maintain this legacy global mapping precisely because it enables rapid, zero-setup exploration of the DOM.

Since you are optimizing your DevTools workflow for rapid exploration, there are a few other console-exclusive shorthands you might find useful that bypass standard DOM queries:

  • $0: This instantly returns the node currently selected in the Elements panel. If you click on any tag in the DOM inspector, switching to the console and typing $0.style gives you immediate access, bypassing the need for an id entirely. (You can also use $1, $2, etc., to walk back through your selection history).
  • $('selector'): A built-in DevTools alias for document.querySelector(). Typing $('.my-class') is much faster than typing out the full document method.
  • $$('selector'): A built-in alias for document.querySelectorAll(). Crucially, in DevTools, this returns a standard JavaScript Array instead of a NodeList, allowing you to immediately chain array methods like .map() or .filter() without converting it first.

(Chronological order restored from this point.)

Me: <body id="page-body" something="non-standard">

For the above, in DevTools console, if I type page-body, it is not recognized. Perhaps that's due to hyphen in the name. pageBody is also not recognized. Is there any workaround?

Gem: The hyphen makes page-body an invalid JavaScript variable name because the engine interprets it as a math expression: the variable page minus the variable body. The browser does not automatically convert these ID mappings into camelCased global variables like pageBody.

However, the browser still successfully created the global reference and attached it to the window object using the exact string. You can bypass the naming restriction by using bracket notation:

  • window['page-body']

Since your goal is rapid DevTools exploration, you can also fall back on the built-in query selector shorthand mentioned earlier, which safely handles any valid CSS selector string:

  • $('#page-body')

Both methods will instantly return the element without forcing you to write out the full document.getElementById() boilerplate.

(Ravi: window['page-body'] as well as $('#page-body') worked.)

Complex selector with querySelectorAll is preferred over imperative JavaScript loop in modern JS apps

Me: The second suggested solution to https://javascript.info/dom-attributes-and-properties#make-external-links-orange exercise uses a complex CSS selector. Related key lines of code are:

    let selector = 'a[href*="://"]:not([href*="http://internal.com"])'
    let links = document.querySelectorAll(selector);

That works and is perhaps more efficient than the first solution of getting all anchor elements using querySelectorAll, then in a loop, going through each link's href attribute (using getAttribute to get HTML source href) and doing above checks within the href. But the first solution is more readable than the complex CSS selector second solution. What would be preferred in modern JS apps?

(Related files in private repo: make-ext-links-orange-ex-1.html and make-ext-links-orange-ex-2.html in dom-props-and-attr folder. Also I later changed the selector to match the suggested solution - 'a[href*="://"]:not([href^="http://internal.com"])')

Gem: The CSS selector approach (Solution 2) is the preferred method in modern vanilla JavaScript development for several structural and performance reasons.

While an imperative JavaScript loop might feel closer to traditional algorithmic programming, modern frontend development heavily favors declarative patterns—telling the browser what you want rather than how to find it.

Here is why the complex CSS selector wins in production:

  • Native Engine Performance: When you pass a complex selector to querySelectorAll, the filtering is executed entirely within the browser's highly optimized native C++ CSS engine. The JavaScript loop approach forces the browser to serialize every single anchor tag, cross the JS/DOM bridge, and execute JavaScript string matching thousands of times, which is significantly slower.
  • Standardized Vocabulary: While a[href*="://"]:not([href*="[http://internal.com](http://internal.com)"]) looks dense, attribute selectors (*= for contains, ^= for starts with, $= for ends with) and the :not() pseudo-class are standard CSS3 fundamentals. Experienced frontend developers parse these one-liners just as easily as a JavaScript if statement.
  • The "Zero JS" Reality: In a real-world vanilla application, a developer wouldn't use JavaScript for this task at all. Because CSS engines are so powerful, they would simply drop that exact same selector directly into their .css file (a[href*="://"]... { color: orange; }), keeping styling logic strictly out of the JavaScript bundle.

The React Contrast Given your background reading and writing React apps, it is worth noting that in a modern framework, you wouldn't use either of these DOM query solutions. Post-render querying is an anti-pattern in React. Instead, you would build a custom <ExternalLink href="..."> component that checks its own href string during the render cycle and conditionally applies a CSS class, entirely bypassing querySelectorAll.

Me: In the React/Next.js apps I read (small to medium size) over past 2 years or so, I did not come across such complex CSS selectors being used to identify which entries match. What you suggested above is what I would come across which is closer to the imperative approach. But is that not a performance issue or does React handle it due to its virtual DOM?

Gem: Your observation is spot on. In the React and Next.js world, you will almost never see complex CSS selectors used to query the DOM, and you are exactly right about why: React's architecture and the Virtual DOM completely flip the performance equation.

In Vanilla JavaScript, the browser has already painted the entire DOM tree. To change a specific set of links, you have to send a search party into the real document to find them. The complex CSS selector is simply the most efficient search party available because it runs in the browser's optimized C++ engine.

React doesn't send search parties because it builds the tree. It already possesses all the data about the elements before they ever touch the screen.

Here is why the component-level conditional approach is not a performance issue in React:

  • In-Memory Evaluation: When a React component receives an href prop, it evaluates your imperative JavaScript condition (like href.includes('http')) entirely in memory. Checking a string on a raw JavaScript object is blazingly fast and requires zero DOM interaction.
  • The Virtual DOM Bypass: Because React evaluates that condition during the render phase, it attaches the resulting CSS class (e.g., className="orange-link") directly to the Virtual DOM node.
  • Direct Painting: When React's reconciliation algorithm finally syncs the Virtual DOM to the real browser DOM, the anchor tag is inserted with the correct class already permanently attached.

The Vanilla JS workflow is: Render → Query → Mutate. The React workflow is: Evaluate Data → Render.

By evaluating the data up front, React entirely eliminates the "Query" step. So while an imperative string-checking loop against live DOM nodes would be a massive performance bottleneck in Vanilla JS, evaluating string props in memory is incredibly cheap. This allows React codebases to remain highly readable and component-focused without paying the DOM-querying performance tax.

append is preferred over appendChild in modern JS apps as append is more flexible; MDN examples use appendChild but that can be ignored

Me: I am now looking at Modifying the document javascript.info lesson. In that context, I tried out below snippet of code. (Inserted line break(s) below to prevent horizontal scroll issue.)

    let li2 = document.createElement('li');
    // li2.innerHTML = "Bye"; // Works
    // li2.appendChild(document.createTextNode("Bye"));
    //  // Works but needs Node and does not
                       // accept string like append()
    li2.append("Bye"); // Works

Looks like the two commented versions and the last uncommented version achieve the same effect from UI point of view. But at DOM object level, is the effect slightly different?

Gem: For a newly created, empty element, all three approaches result in the exact same final DOM structure: an <li> element containing exactly one child, which is a Text node with the value "Bye".

However, the execution mechanics and how they handle existing content differ significantly:

  • li2.innerHTML = "Bye" (The HTML Parser): Passes the string to the browser's heavy HTML parser. It destroys any existing children in li2 and replaces them. If the string contains user-submitted data, it exposes the application to Cross-Site Scripting (XSS) vulnerabilities.
  • li2.appendChild(document.createTextNode("Bye")) (The Classic Node API): Bypasses the HTML parser entirely. It safely creates a Text node and adds it to the end of the child list, preserving any existing children. It strictly requires a DOM Node object as an argument and will fail if passed a raw string.
  • li2.append("Bye") (The Modern API): Bypasses the HTML parser. When passed a string, the browser automatically executes the equivalent of createTextNode under the hood. It safely appends to the end of the child list and, unlike appendChild, can accept multiple strings and Nodes simultaneously (e.g., li2.append("Text ", spanNode, " more text")).

In modern Vanilla JavaScript, li2.append("Bye") is the preferred standard because it combines the performance and security of createTextNode with cleaner, more flexible syntax. ...

Me: I see. The javascript.info lesson uses append and innerHTML property but not appendChild. However, MDN, in its DOM intro page, for Accessing the DOM section's very simple example, uses appendChild. That led me to think that appendChild is a currently used method. But clearly append is more powerful. Why does MDN use appendChild instead of append in its first example of creating a DOM element in its intro page? I am confused.

Gem: MDN defaults to appendChild in its introductory examples primarily for pedagogical reasons: it forces the learner to explicitly interact with the DOM as a strict tree of Node objects rather than hiding the mechanics behind syntactic sugar.

Here is why the documentation presents it this way, even though append is the modern standard:

  • Teaching the Tree Architecture: To use appendChild, you must explicitly call document.createTextNode(). This teaches the fundamental DOM concept that text on a webpage is not merely a string property, but a discrete structural object in the memory tree. append obscures this architectural reality by silently converting strings into text nodes under the hood.
  • The Original Standard: appendChild is one of the oldest methods in the browser ecosystem, introduced in the DOM Level 1 specification in 1998. append (part of the ParentNode API) is a modern addition. Understanding the legacy method is essential because the vast majority of the web's foundational codebase was built using it.
  • Documentation Inertia: MDN is a community-edited wiki that has evolved over decades. Introductory examples written years ago often remain untouched if they successfully teach the core concepts of the DOM, even if newer, more convenient API wrappers exist today.

Your instinct is correct: append is much more powerful. In modern vanilla JS development, you should absolutely use append. But from an academic standpoint, MDN shows you appendChild first so you understand exactly what the browser is doing behind the scenes.

To assign raw text, append or textContent is preferred instead of innerHTML

Me: Got it. Good explanation. Now about why javascript.info is using liFirst.innerHTML = 'prepend'; when liFirst.append('prepend') would have been a more appropriate way, given what you said earlier. Note that it uses append elsewhere like ol.append(liLast); to add a created li element to an ol element. Ur thoughts pl.

Gem: You have spotted a genuine inconsistency in the tutorial's code, and your instinct is absolutely correct. Using innerHTML to insert a plain text string into a newly created element is an anti-pattern in modern production code.

The author likely chose innerHTML in this specific snippet for pedagogical convenience rather than architectural best practice:

  • Flexibility for Experimentation: Tutorials often use innerHTML as a forgiving catch-all. If a learner decides to play with the code and changes the string to <strong>prepend</strong>, innerHTML parses it correctly. If the author had used append('<strong>prepend</strong>'), the learner would see the literal, unparsed HTML tags printed on the screen, which might confuse them during an introductory lesson.
  • Managing Cognitive Load: The primary goal of that specific code block is to teach the structural insertion methods (ol.prepend and ol.append). By falling back on the older, universally recognized innerHTML to quickly populate the node, the author keeps the reader's attention focused on how the element is placed into the list, rather than how the text is placed into the element.

In a real-world Vanilla JS application, you are completely right. If you are inserting pure text into a new element, you should bypass the browser's HTML parser entirely to avoid overhead and potential security risks.

The two correct modern approaches are:

  • liFirst.append('prepend'): Just as you suggested, this cleanly appends a text node under the hood.
  • liFirst.textContent = 'prepend': This is the most explicit and performant way to assign raw text to a node, instantly overwriting any existing text content.

You can safely treat the tutorial's use of innerHTML for plain text as a lazy shortcut.

Me: Good response again. Things are becoming clearer for me. One of the challenges with learning DOM API is that for many operations, there are multiple ways of achieving the same UI outcome. Knowing which way is the accepted pattern in modern JS dev, can be hard to figure out. Using innerHTML property to add text when you have textContent property as well as append method, seems to be inappropriate in this case, as you have said.

Gem: ... Because browsers have a strict mandate to never break older websites, legacy methods are rarely deprecated and never removed. Instead, the W3C just layers newer, safer, and more ergonomic APIs on top of the old ones. This leaves modern developers staring at three or four different ways to do the exact same thing, forced to figure out which one was written in 1998 and which one was standardized in 2017.

To permanently solidify your mental model for these three specific text-handling properties moving forward:

  • Use textContent when you want to safely and instantly overwrite everything inside an element with raw text.
  • Use append() when you want to safely drop new text or elements at the very end of a container, preserving what is already inside.
  • Use innerHTML strictly when you are handing the browser a string of actual HTML tags to parse, and only when you absolutely trust the source of that string.

Since we are untangling the overlapping methods in the "Modifying the Document" chapter, would you like to look at how the modern before(), after(), and replaceWith() APIs finally replaced the notorious complexity of the legacy insertBefore() method?

MDN DOM Introduction and Guides pages - Initial study round

Me: 17 Nov. Over past few days, off and on, including today, I went through following MDN documentation pages (exclusions mentioned) which are Introduction and Guides related pages. MDN documentation is much more precise than Javascript.info tutorial but has lot of material and is harder to read. Javascript.info tutorial and Gemini discussions as captured above helped in these MDN pages becoming easier reads now for me though I am not trying to understand every detail as of now. That is quite significant I think as MDN is the reference site which I may visit often when I get back to regular web dev.

The above pages content, being associated with WebIDL, comes across as standard OOAD stuff - so more C++ and C#/Java type than JavaScript. I like the precision of terminology in these pages.

About Visitor

Google Search AI:

In this MDN guide (Selection and traversal on the DOM tree), visitor is a callback function passed into a tree-walking algorithm to define what action to perform on each node as it is reached.

It is not a built-in WebIDL keyword or browser API, but a conceptual placeholder from the Visitor design pattern used to explain how DOM traversal and selection work under the hood.

(Ravi: Simple explanation in geeksforgeeks.org: )Visitor design pattern

Gem: Your observation about the DOM reading like C++ or Java is historically and technically exact. When the W3C drafted the original DOM Level 1 specification in 1998, they explicitly designed it to be a language-agnostic, object-oriented API. WebIDL exists precisely so the exact same DOM structure can be implemented in C++ (inside the browser engine), Java, and JavaScript. That strict OOAD lineage is exactly why you see rigorous inheritance chains, discrete node types, and rigid interface contracts throughout the documentation.

Graduating from tutorial sites to MDN is a major milestone. MDN reads like a technical specification because it serves as the ultimate source of truth for browser vendors. Being able to comfortably parse it gives you a massive advantage for jumping back into active development, as it eliminates the guesswork of relying on third-party interpretations.

The "Visitor" concept perfectly highlights the bridge between classical OOAD and modern JavaScript.

  • In classic C++: The Gang of Four Visitor pattern requires a rigid architecture—an abstract Visitor class, multiple concrete visitor implementations, and accept(Visitor* v) methods on every node to handle double-dispatch.
  • In JavaScript: Because functions are first-class objects, the heavy architectural boilerplate evaporates. The "Visitor" simply becomes a callback function passed into a traversing loop.

The conceptual intent—separating the algorithm of walking the tree from the specific action performed at each node—remains exactly the same. However, JavaScript's functional nature reduces what would be a multi-file OOAD pattern in C++ down to a simple, inline callback function. ...

insertAdjacentHTML is used in modern Vanilla JS apps to inject raw string of HTML into the DOM and is preferred over innerHTML += ...

From https://javascript.info/modifying-document#insertadjacenthtml-text-element : "elem.insertAdjacentHTML(where, html)"

Is the above API used in modern JS apps?

Gem: insertAdjacentHTML is heavily used in modern Vanilla JavaScript applications when a developer needs to inject a raw string of HTML into the DOM. It is the high-performance, non-destructive alternative to the notorious innerHTML += ... anti-pattern.

Here is why it is preferred in the modern Vanilla ecosystem:

  • State Preservation: If you use container.innerHTML += '<p>New</p>', the browser completely destroys every existing child node inside the container and rebuilds them from scratch. Any event listeners attached to those existing children are instantly wiped out. insertAdjacentHTML parses the new string and drops the resulting nodes exactly where you want them, leaving the existing DOM tree and its event listeners completely untouched.
  • Surgical Precision: The four positional keywords (beforebegin, afterbegin, beforeend, afterend) give you pinpoint placement accuracy. It is essentially the string-parsing equivalent of the modern before(), prepend(), append(), and after() node methods.
  • Engine Performance: Because it doesn't force the browser to re-serialize and re-parse the existing children, it is significantly faster than appending via innerHTML.

The Framework Contrast While it is a staple in Vanilla JS, you will almost never see this API in a React or Next.js codebase. Because React uses the Virtual DOM to reconcile state changes, manually injecting HTML strings to bypass React's render cycle would cause the framework to lose track of the DOM structure and eventually crash on subsequent updates.

The Security Caveat Because insertAdjacentHTML invokes the browser's HTML parser, the same rules apply to it as innerHTML. If you pass unsanitized user input into the html parameter, you are opening the door to Cross-Site Scripting (XSS) attacks. If you only need to insert plain text, append() or textContent remains the correct choice.

Me: I was wondering about the XSS vulnerability but if the developer is not using any user input, then we don't have that vulnerability. Therefore, it would be fine to use it in vanilla JS apps. Am I right?

Gem: You are absolutely right. If the HTML string is entirely hardcoded or generated strictly from trusted internal state—with absolutely zero user input mixed in—there is no XSS vulnerability.

XSS fundamentally requires an injection vector. If a malicious actor cannot manipulate the string being passed to the browser's HTML parser, they cannot execute arbitrary code.

In fact, using insertAdjacentHTML with static strings is a very common and highly efficient pattern in vanilla JS development for building UI scaffolding, injecting SVG icons, or dropping in empty loading states:

// Completely safe: no user input or untrusted variables involved
const loadingSkeleton = `
  <div class="skeleton-wrapper">
    <div class="skeleton-avatar"></div>
    <div class="skeleton-text"></div>
  </div>
`;
container.insertAdjacentHTML('beforeend', loadingSkeleton);

The Maintenance Caveat The only risk here is human error during future updates. A string that starts out entirely static might later be modified to include a dynamic variable.

If a safe template like <div class="msg">Hello Guest</div> is later updated to <div class="msg">Hello ${userName}</div>, and userName is pulled from a URL parameter or an external database, a secure implementation instantly becomes vulnerable.

As long as you maintain strict hygiene about ensuring untrusted variables are never interpolated into those template strings, using insertAdjacentHTML for structural rendering is a perfectly safe, industry-standard approach.

Robust sanitization libraries like DOMPurify can be used to protect against XSS vulnerability when using insertAdjacentHTML or innerHTML

Me: Good points. If we use sanitization libraries, would we be protected against such vulnerability even when we include user input data in the inserted HTML (but after sanitization)?

Gem: Yes, that is exactly the correct approach. Using a robust sanitization library guarantees that you can safely inject dynamic HTML strings containing user input without risking XSS vulnerabilities.

In the modern JavaScript ecosystem, the undisputed industry standard for this task is DOMPurify. It is a heavily tested, security-focused library used precisely to clean untrusted HTML before it touches an API like insertAdjacentHTML or innerHTML.

Here is how it protects your application:

  • Inert Parsing: When you pass a string to DOMPurify, it does not immediately render it. Instead, it uses the browser's DOMParser to create a disconnected, inert document tree in memory where malicious scripts cannot execute.
  • Surgical Extraction: It traverses this hidden tree and aggressively strips out anything dangerous. It removes <script> tags, inline event handlers (like onload or onerror), and malicious href attributes (like javascript:alert(1)), while leaving safe tags (like <b>, <i>, or <p>) entirely intact.
  • Outputting Safe Strings: It serializes the cleaned tree back into a standard HTML string, which you can then safely pass to the DOM.

In practice, your code would look like this:

// Untrusted user input containing a common XSS vector
const userInput = `<img src="x" onerror="alert('Hacked!')"> <b>Hello Ravi</b>`;

// 1. Sanitize the string (strips the malicious onerror attribute)
const cleanHTML = DOMPurify.sanitize(userInput);
// cleanHTML is now: `<img src="x"> <b>Hello Ravi</b>`

// 2. Safely insert into the live DOM
container.insertAdjacentHTML('beforeend', cleanHTML);

As an architectural note for the future: the W3C is currently drafting a native HTML Sanitizer API (introducing methods like setHTML() to replace innerHTML). However, because browser support is still experimental, DOMPurify remains the mandatory dependency for this workflow in production vanilla JS apps today.

document.querySelector('p')?.remove(); - modern, idiomatic approach to check for existence and then remove

(For removing the first paragraph element in document)

Gem: ... modern, idiomatic approach ... using Optional Chaining (?.):

document.querySelector('p')?.remove();

Here is why this is often considered "better" in modern vanilla JS apps:

  • Conciseness: It eliminates the need for an if statement and a temporary variable.
  • Short-circuiting: The ?. operator automatically checks if the left side evaluates to null or undefined. If querySelector doesn't find a paragraph, the engine simply stops executing that line immediately, completely safely.

p.remove() is syntactic sugar for looking up the node's parent and executing equivalent of removeChild

Me: ... I do find it a little strange that we remove the node/element directly without any reference to the container. I thought we would have to say container.remove() and specify which child we want to be removed. Ur thoughts pl.

Gem: Your architectural instinct is absolutely correct. In classic computer science tree structures, a node cannot remove itself from the tree. The parent node holds the pointer to the child, so the parent must be the one to break that link.

For the first 15+ years of web development, the DOM operated exactly the way you just described. If you wanted to remove a paragraph, you had to ask its container to do it using the legacy removeChild() method:

let p = document.querySelector('p');
if (p && p.parentNode) {
  p.parentNode.removeChild(p);
}

Because of the strict Object-Oriented nature of the original DOM Level 1 specification, this was the only way to modify the tree. The browser engine required you to explicitly navigate up to the parent just to tell it to delete the child you already had a reference to.

Developers universally found this verbose and annoying. It was one of the primary reasons libraries like jQuery became massively popular in the 2000s—they provided a simple .remove() shortcut.

Eventually, the W3C recognized this friction. When they modernized the DOM API (introducing the ChildNode interface), they added p.remove() as native syntactic sugar.

When you call p.remove() in a modern application, the browser's C++ engine is still doing exactly what you expect under the hood: it looks up the node's parent and executes the equivalent of removeChild. The API was simply updated to prioritize developer ergonomics over strict tree-traversal theory.

Single Instance Rule: A Node object cannot exist in two places in DOM simultaneously; So move operations automatically remove from source parent and add to target parent

Me: Following example is from javascript.info:

...
  // no need to call remove
  second.after(first); // take #second and after it insert #first
...

Is a similar 'developer ergonomics' shortcut in play here, where one does not go through steps of removal from one parent/container followed by addition to another parent/container?

Gem: Yes, you have correctly identified another massive ergonomic shortcut, but unlike the .remove() method, this specific behavior is not a modern addition—it is a fundamental, foundational rule of how the DOM architecture operates under the hood.

This behavior is driven by the Single Instance Rule of the document tree.

In the DOM, a Node object is a unique memory reference. A single node cannot exist in two places in the document tree simultaneously. Because of this architectural constraint, the browser engine's insertion algorithms (whether you use the modern .after() or the legacy .appendChild()) are hardcoded to perform an automatic, atomic move.

Here is exactly what happens when you execute second.after(first):

  1. Reference Check: The engine looks at #first and sees that it already has a parentNode.
  2. Automatic Detachment: The engine safely unlinks #first from its current parent in memory.
  3. Reattachment: It immediately links #first into its new position after #second.

The browser handles this detachment and reattachment in a single, atomic operation. If developers were forced to manually call remove() before moving a node, it would introduce a massive risk of memory leaks or lost references during complex UI operations, like sorting a list or building a drag-and-drop interface.

By making insertion inherently destructive to the node's previous position, the DOM API saves developers from writing tedious cleanup code and guarantees the tree remains structurally valid.

cloneNode does not copy event listeners and does not handle duplicate id attributes; cloneNode is used with <template> tag in modern JS

Me: cloneNode() with deep or shallow parameter is quite an interesting API. (Related section in tutorial: https://javascript.info/modifying-document#cloning-nodes-clonenode , related file in private repo: cloneNode.html in modifying-document folder.)

Gem: cloneNode() is essentially the DOM's native factory method. The boolean parameter dictating a deep (true) or shallow (false) clone is powerful, but it comes with a few architectural traps that frequently catch developers off guard.

Here is how the two modes behave under the hood, and the specific gotchas associated with them:

1. The Shallow Clone (cloneNode(false)) Trap When you perform a shallow clone on an element like <button class="btn">Submit</button>, you might expect to get an exact copy of that button. Instead, you get <button class="btn"></button>. Because the text "Submit" is actually a discrete TextNode child sitting inside the button, a shallow clone completely ignores it. It only copies the element itself and its attributes. Shallow clones are typically only useful when you want to duplicate a container's styling and classes but plan to populate it with entirely new data.

2. The Deep Clone (cloneNode(true)) This recursively copies the element, its attributes, and its entire descendant tree (including all text nodes). This is the mode you will use 99% of the time in real-world applications when you need to duplicate a row in a table or add a new input group to a form.

The Two Major Architectural Gotchas

  • The Event Listener Wipeout: cloneNode() does not copy event listeners attached via JavaScript's addEventListener(). If you clone a fully functional "Delete" button, the clone will look identical but do absolutely nothing when clicked. (It will copy inline HTML handlers like onclick="...", but since those are an anti-pattern in modern JS, you should rely on Event Delegation on a parent container to handle events for cloned children).
  • The ID Collision: If the node you are deep-cloning contains elements with id attributes, inserting the clone into the document immediately breaks HTML validation by creating duplicate IDs. You must manually traverse the cloned tree and update or remove the IDs before inserting it.

The Modern Killer Use Case: <template>

In modern Vanilla JS and Web Components, cloneNode(true) has found its ultimate purpose alongside the HTML <template> tag.

Browsers parse <template> tags but do not render them on the screen. Instead of building complex DOM structures via string interpolation (insertAdjacentHTML) or endless document.createElement calls, modern developers put the markup in a <template>, grab it in JS, and simply call template.content.cloneNode(true) to stamp out safe, exact replicas whenever they need to mount a new UI component.

remove() method is in ChildNode interface mixin which is implemented by Element, CharacterData (which includes Text and Comment nodes), and DocumentType

Me: https://javascript.info/modifying-document#node-removal says: "To remove a node, there’s a method node.remove()". ...

Gem: ... In the DOM's strict WebIDL class hierarchy, the base Node interface does not possess a .remove() method. It only defines .removeChild().

The .remove() method actually belongs to a separate interface mixin called ChildNode. This mixin is implemented by Element, CharacterData (which includes Text and Comment nodes), and DocumentType.

Because almost every tangible piece of the DOM tree that a developer interacts with inherits from this ChildNode mixin, the .remove() method is universally available on elements and text. The javascript.info author is using the word "node" in a loose, colloquial sense ("a piece of the document") rather than referring to the strict Node interface.

This perfectly illustrates the C++-style OOAD precision of MDN that you noticed earlier. MDN enforces the strict inheritance contracts, documenting .remove() only on the specific interfaces that actually implement it, whereas the tutorial abstracts the class hierarchy away for beginner simplicity.

Me: Hmm. But why is elem.childNodes[0].remove(); allowed? (it works). ...

Gem: Your C++ and OOAD instincts are right on the money here. The reason it works comes down to classical polymorphism—specifically the difference between a method's return signature and the actual runtime type of the object.

The childNodes property returns a NodeList. By definition, a NodeList guarantees that every item inside it inherits from the base Node interface.

However, you never actually instantiate a raw, abstract Node in the DOM. At runtime, the object sitting at childNodes[0] is a concrete subclass—usually an Element (like a <div>) or a Text node.

Here is exactly how the engine resolves that call:

  1. The Runtime Instance: childNodes[0] might return a Text node object.
  2. The Inheritance Chain: A Text node inherits from CharacterData, which inherits from Node.
  3. The Mixin: As we established, CharacterData (and Element) implement the ChildNode mixin.
  4. Dynamic Dispatch: Because JavaScript is dynamically typed, the engine doesn't restrict you to the base Node interface. When you call .remove(), the engine looks at the actual runtime instance, traverses up its prototype chain, finds .remove() on the ChildNode mixin, and executes it.

In a strict, statically typed language like C++, doing this directly on an array of base Node* pointers would throw a compile-time error because remove() isn't on the base class. You would be forced to dynamic_cast the pointer to an Element* or CharacterData* first. JavaScript bypasses that friction, looking purely at the concrete object holding the data at the moment of execution.

Me: Oh! Polymorphism comes into play. Also even Text nodes implement remove as CharacterData implements it. Got it.

I got confused by 'To remove a node, there’s a method node.remove()' as meaning that it is a method implemented on Node (not noting the lowercase node). What the tutorial meant was that if we have JavaScript variable called node which holds a DOM node, we have access to a method node.remove (where node is variable name). Am I on right track here?

Gem: You are exactly on the right track. In JavaScript tutorials, lowercase names like node, elem, or element are almost universally used as generic placeholder variables representing a runtime instance.

The tutorial was simply saying, "If you have a variable named node that holds a piece of the DOM, you can call .remove() on it."

This highlights the exact stylistic difference between teaching material and technical specifications:

  • Tutorials use instance variables (node.remove()) to show you what the code looks like when you type it in your editor.
  • MDN and WebIDL use PascalCase interface names (Element.remove(), Node.removeChild()) to document the strict C++ inheritance architecture under the hood.

Your realization perfectly bridges the gap between the forgiving, dynamically-typed nature of JavaScript and the strict OOAD architecture that actually powers the browser engine.

Me: Uploaded file (clearElement-ex.html in modifying-document folder in private repo) has various solutions and an improper solution to clear exercise. Pl. examine code and comments for accuracy.

Gem: Your analysis of the code and the accompanying comments in "clearElement-ex.html" is technically precise and completely accurate. You have successfully identified several classic DOM manipulation traps.

Here is a detailed breakdown of your implementations:

  • The Improper Solution (elem.children reverse loop): Your comment perfectly diagnoses the flaw. elem.children returns an HTMLCollection that strictly contains Element nodes (the <li> tags) and ignores the Text nodes (the whitespace and newlines between the tags in your HTML markup). If you only remove the elements, those invisible text nodes are left behind in the DOM tree. Furthermore, your architectural insight to loop in reverse is exactly right. elem.children is a live collection. If you loop forward (i++) and remove index 0, the element at index 1 instantly shifts into index 0. The loop then advances to index 1, skipping an element entirely. Iterating backwards safely drains a live collection without index shifting collisions.

  • The innerHTML = "" Solution: Your comment that this "works" is correct. This immediately commands the browser engine to destroy the entire descendant tree. In modern applications, elem.textContent = "" is often preferred for completely clearing elements because it entirely bypasses the HTML parser, making it marginally faster and immune to parsing overhead.

  • The childNodes Reverse Loop: Your comment that this code works is correct. Because elem.childNodes returns a NodeList containing all node types (Elements, Text, Comments), looping through it in reverse successfully wipes the container completely.

  • The while (elem.firstChild) Loop: Your assessment is correct. This is the most idiomatic, classic algorithm for draining a DOM node imperatively. Because the DOM updates live, calling .remove() on firstChild automatically promotes the next sibling into the firstChild slot on the very next cycle. The loop cleanly exhausts the tree without requiring manual index tracking. ...

Using JSDoc comments to help VS Code Intellisense to recognize function argument types and also function local variables to provide correct autocomplete suggestions

18 Nov 2026

JSDoc comments helps VS Code Intellisense to recognize function argument types and provide correct autocomplete suggestions as shown in example below.

<script>
    'use strict'
    /**
     * 
     * @param {HTMLElement} elem 
     */
    function clear(elem) {
    ...
    }  

Without JSDoc comments, VS Code does not provide HTMLElement object properties and methods in autocomplete suggestions.

24 Nov 2026 Update

When we are dealing with a function local variable (as against function argument) which is expected to hold a particular object like HTMLUListElement but is not recognized as such by VS Code Intellisense:

    /** @type {HTMLUListElement | null} */
    const ul = fnx(document); // Hovering over ul shows: 'const ul: HTMLUListElement | null'
    
    const ul2 = fnz(document); // Hovering over u2 shows: 'const ul2: any'

end 24 Nov 2026 Update

In .js file, typing /** followed by Enter, just above a function, creates JSDoc comments shell. But that did not work within script element in .html file.

Related VS Code extension that I have not tried out: Document This, https://marketplace.visualstudio.com/items?itemName=oouo-diogo-perdigao.docthis, "Automatically generates detailed JSDoc comments in TypeScript and JavaScript files."

(I shared above with Gem.)

Gem: Your addition is highly accurate and captures a crucial workflow technique for modern vanilla JavaScript development. Using JSDoc to power Intellisense is the industry-standard way to get strict, C++-style type hinting in your editor without having to set up a full TypeScript compilation pipeline.

Here is a breakdown of your observations and a minor formatting catch:

  • The HTML <script> Limitation: Your observation about the /** shortcut failing in .html files is entirely correct. This happens because VS Code delegates .html files to its HTML Language Server. This server treats JavaScript inside <script> tags as a secondary, embedded language and disables many advanced editor features, including snippet auto-generation.
  • The Workflow Solution: The easiest way to restore the /** auto-generation without an extension is to move your JavaScript into a dedicated .js file and link it via <script src="..."></script>. Once in a native .js file, the dedicated JavaScript Language Server takes over and restores all Intellisense features.
  • The "Document This" Extension: This is a popular and reliable extension for developers who write heavily documented vanilla JS, though the built-in VS Code JSDoc support usually covers 90% of use cases once you are working in a .js file.

...

Yield to browser for painting while in sync loop: Convert to async and a) await scheduler.yield() - simple but not universally supported OR b) await promise resolved on timeout - more universally supported

(This was part of an exchange with Google Search AI - GSAI.)

(create-list-ex-2.html in modifying-document folder in private repo has both the approaches. Snippets from it are given below. The small page uses prompt() in a loop. prompt() is synchronous and freezes the browser tab. ... Inserted line break(s) below to prevent horizontal scroll issue.)

    // // Yield briefly so the browser paints the page/item before
    // // freezing on prompt()
    // // Works on most browsers
    // await new Promise(resolve => setTimeout(resolve, 50));
    // Yield back to the browser event loop so it can paint before
    // the next prompt
    // Works for me but may not work on some older browsers
    await scheduler.yield();

GSAI: The Modern Native Solution: scheduler.yield()

Because developers frequently wanted a cleaner way to pause heavy loops without setTimeout hacks, modern browsers introduced scheduler.yield(). (Inserted line break(s) below to prevent horizontal scroll issue.)

async function doWork() {
  ulElem.append(li);
  
  // Tells the browser: "Run any urgent tasks (like painting),
  //  then come right back here"
  await scheduler.yield(); 
}

Unlike setTimeout, scheduler.yield() doesn't arbitrarily wait 50ms—it gives the browser just enough time to handle user input and paint the screen, then immediately resumes your function with high priority. (Note: Because prompt() aggressively blocks rendering in some browsers, a small setTimeout is still safer specifically when working with prompt()).

...

Me: It (scheduler.yield) worked for me (latest or close to latest Chrome on Win 11). It is simpler than the promise, resolve, setTimeout 50 ms line. But from what you say, scheduler.yield() may not work properly on some browsers whereas the promise, resolve, setTimeout 50 ms approach may work on most browsers. Did I get this correctly?

GSAI: Yes, you understood that completely right.

Because scheduler.yield() is a newer API, its behavior and availability vary across browsers, whereas new Promise(resolve => setTimeout(resolve, 50)) works reliably everywhere.

Why setTimeout Is More Universal

  • 100% Browser Support: Promise and setTimeout have been supported across every major browser (Chrome, Edge, Firefox, and Safari) for over a decade, whereas scheduler.yield() still lacks universal support in older browser versions and certain engines like Safari.
  • Guaranteed Paint Window: scheduler.yield() only yields to the browser's task queue and resumes as fast as possible. On slower devices or different rendering engines, your script might resume before the next screen refresh (16.6ms on a 60Hz monitor), allowing prompt() to block the paint. A 50ms timeout spans roughly three screen refresh cycles, giving any browser plenty of time to finish drawing.

Best of Both Worlds (Optional Fallback)

If you ever want the cleanliness of scheduler.yield() with a safety net for browsers that don't support it yet, you can define a tiny helper at the top of your script:

const yieldToBrowser = () => 
  globalThis.scheduler?.yield 
    ? scheduler.yield() 
    : new Promise(resolve => setTimeout(resolve, 50));

// Then inside your loop:
await yieldToBrowser();

For your current learning exercise on Chrome, sticking with await scheduler.yield() is totally fine and very clean.

scheduler.yield() and the yield keyword used in generator functions are two completely unrelated features in JavaScript

Me: Just wanted to confirm that scheduler.yield() is unrelated to yield statement associated with generators in JavaScript.

GSAI: Yes, you are completely right. scheduler.yield() and the yield keyword used in generator functions are two completely unrelated features in JavaScript that happen to share the same English word.

Key Differences

  • yield (Generator Keyword): This is a built-in JavaScript language syntax keyword used only inside function* generator functions. It pauses a generator and passes a value back to the caller, without freeing the browser's main thread or letting the screen paint.
  • scheduler.yield() (Browser Web API): This is a method on the browser's Scheduler object that returns a Promise. When combined with await inside an async function, it yields control of the main thread back to the browser's event loop so pending tasks like UI painting can run.

Why They Share the Name

  • Similar concept, different layer: Both use the word "yield" because they pause execution and hand control over to something else—a generator yields control to whoever called .next(), while scheduler.yield() yields control to the browser's task scheduler.

<li> element allows virtually all standard block-level and inline elements—not just text and nested lists; In recursive functions, modern JS devs prefer simpler code over avoiding additional function call

19 Nov 2026

(Some points from Google Search AI exchanges as I was doing Javascript.info Create a tree from the object exercise. Related files in private repo are create-tree-from-obj-ex-1.html and create-tree-from-obj-ex-2.html in modifying-document folder.)

GSAI: (An) <li> element can contain almost any HTML element.

In the HTML5 specification, the <li> element allows flow content, which includes virtually all standard block-level and inline elements—not just text and nested lists.

Common Elements You Can Put Inside <li>

  • Inline & Text Formatting: <a> (links), <strong>, <em>, <span>, <code>
  • Structural & Block Elements: <p> (paragraphs), <div>, <article>, <blockquote>
  • Headings: <h1> through <h6> (often used in card grids or news feeds structured as lists)
  • Media & Interactive Elements: <img>, <svg>, <button>, <input>, <details> / <summary> (great for native collapsible lists)
  • Other Lists: <ul>, <ol>, <dl> (description lists)

Valid Example with Multiple Elements

Because <li> acts as a general container, you can build complex layouts like navigation items, product cards, or accordion trees inside a single list item:

<ul>
  <li>
    <h3>Tree</h3>
    <p>Perennial plants with elongated stems.</p>
    <ul>
      <li>
        <a href="/sequoia">Sequoia</a>
        <span class="badge">Huge</span>
      </li>
      <li>
        <a href="/magnolia">Magnolia</a>
        <span class="badge">Flowering</span>
      </li>
    </ul>
  </li>
</ul>

The Few Exceptions

The only things you cannot put inside an <li> are:

  • Document-level structural tags (<html>, <head>, <body>, <meta>, <title>)
  • Elements restricted to specific parents (such as <td>, <tr>, <option>, or another bare <li> without a wrapping <ul> or <ol>)

Me: Now about placement of nested list in an li element. Can it be placed anywhere? I see that typically it is placed at the end of the li element.

GSAI: Yes, a nested list can technically be placed anywhere inside an <li> element, though placing it at the end is the standard convention for readability and accessibility.

In HTML5, an <li> allows any sequence of flow content, so the browser and HTML validator don't enforce a strict order for child elements.

Valid Placement Options

  • At the end (Standard): Placing the <ul> or <ol> after the item's label, links, or description matches how people read outlines and keeps the parent label right next to its bullet point.
  • In the middle: You can place a nested list between two paragraphs if the content flows naturally that way (for example, introducing sub-items and then adding a concluding note about the parent item).
  • At the beginning: Technically valid, though rarely done because the parent item's label ends up below its own sub-items.

Example: Nested List in the Middle of an <li>

<ul>
  <li>
    <p><strong>Fish</strong> come in many varieties:</p>
    <ul>
      <li>Trout</li>
      <li>Salmon</li>
    </ul>
    <p>Both species are popular in freshwater and marine ecosystems.</p>
  </li>
</ul>

Why Placing It at the End Is Best Practice

  • Screen Reader Clarity: Assistive technologies read the DOM from top to bottom. Having the parent title first immediately tells the user what the upcoming sub-list belongs to.
  • CSS & JavaScript Simplicity: Most CSS menu frameworks and tree-view scripts assume the nested <ul> is the last child (li > ul:last-child) so they can easily position dropdowns or collapse everything after the header row.

(Ravi: One of the solutions provided by Javascript.info for above exercise used for .. in instead of for .. of with Object.entries(). I asked about it ...)

GSAI: ... For a modern JavaScript tutorial, rewriting that loop with for...of and Object.entries() would be cleaner, safer, and more idiomatic ...

Why for...of + Object.entries() Is Better Here

  • Teaches Safer Habits: In a tutorial, learners often copy-paste patterns into real apps where objects might inherit enumerable properties (or come from libraries/older code that modified Object.prototype). Object.entries() avoids that trap without needing Object.hasOwn().
  • Eliminates Repeated Property Lookups: With for...of, you destructure [key, value] immediately instead of writing obj[key] inside the loop body.
  • Cleaner Base Case Handling: When obj is {} (like "trout": {}), Object.entries({}) returns an empty array [], the loop skips immediately, and it cleanly returns ''.

...

Object.keys(obj).length being 0 is standard way in modern JS apps to check if object is empty.

...

(About simpler code with addl fn call vs. avoiding additional function call, code using recursion:)

GSAI: In modern JavaScript, both approaches are acceptable, though letting the recursive call handle the empty object (the javascript.info style) is slightly more common because developers prioritize code simplicity over saving function call overhead.

...

Why Modern JS Often Skips the Pre-Check (javascript.info approach)

In modern JS codebases (like React, Node, or TypeScript projects), developers tend to favor single-responsibility base cases inside recursive functions:

function createTreeText(data) {
  const entries = Object.entries(data);
  if (!entries.length) return ''; // Single base case handles everything

  let li = '';
  for (const [key, value] of entries) {
    li += `<li>${key}${createTreeText(value)}</li>`;
  }
  return `<ul>${li}</ul>`;
}
  • DRY (Don't Repeat Yourself): Checking emptiness inside the function means you only check for empty data in one place, rather than checking it before the call and handling an empty root object inside the function anyway.
  • JIT Optimization: Modern JS engines (like V8 in Chrome/Node) aggressively inline small recursive functions and optimize stack frames, making an extra call on a leaf node essentially free in typical UI code.
  • Readability First: Keeping the template literal free of nested ternaries (${... ? ... : ''}) makes complex HTML templates easier to scan when attributes, classes, or event handlers are added later.

...

Bottom Line

In a modern JS code review, nobody would reject (version avoiding addl function call)—it's concise, clear, and idiomatic. At the same time, writing the unconditional recursive call is equally standard when keeping JSX or template strings as flat as possible. ...

...

if is preferred over && for actions; building <ul> subtree in memory with single DOM insertion at the end is recommended

(This continues above section. The following are related to create-tree-from-obj-ex-1A.html file in modifying-document folder in private repo.)

Me: In below code, in modern JS, I believe if check is preferred even if it is 3 lines as against 1 line with &&. Am I right?

        // ulChild && li.append(ulChild);
        if (ulChild) {
          li.append(ulChild)
        }

GSAI: Yes, you are right. For executing a side effect like append(), a standard if statement is strongly preferred over short-circuiting with && in modern JavaScript.

Why if Is Preferred Over && for Actions

  • Intent & Readability: Logical operators (&&, ||) are meant to evaluate and return values (like const name = user && user.name). Using && just to trigger a function call or DOM mutation hides control flow inside an expression.
  • Linter Enforcement: Industry-standard linters like ESLint explicitly flag this pattern with the no-unused-expressions rule because an expression statement whose return value is thrown away looks like a mistake.
  • Debugging: Setting a breakpoint or adding a console.log inside a multi-line if block is effortless compared to splitting up a one-line && expression.

When Short-Circuiting Is Idiomatic

You will still see && used heavily in React / JSX templates—not for side effects, but because JSX only accepts expressions that evaluate to a value:

// Idiomatic in React JSX (evaluating a value to render)
<li>
  {key}
  {ulChild && <ul>{ulChild}</ul>}
</li>

In plain imperative JavaScript (like DOM manipulation), stick with your if (ulChild) block—it's cleaner, clearer, and passes standard team linters out of the box.

...

  • XSS-Safe Text Assignment: Using li.textContent = key is much safer than innerHTML because any special characters (<, >, &) in your object keys are automatically escaped as text nodes.
  • (Ravi: I raised a question about this point in the next message:) Single DOM Insertion (Great Performance): Building the entire detached <ul> subtree in memory first and calling container.append(ul) once at the end triggers only a single browser reflow/repaint.
  • Clean Base Case: if (Object.keys(data).length === 0) return; cleanly prevents empty <ul></ul> elements on leaf nodes and handles an empty root {} without appending anything to container.

...

Me: You had written: "Single DOM Insertion (Great Performance): Building the entire detached <ul> subtree in memory first and calling container.append(ul) once at the end triggers only a single browser reflow/repaint." But in this simple page's case, JavaScript's run to completion guarantee will ensure that browser will get a chance to paint the DOM only after the script finishes. So does not matter whether attach <ul> subtree at the beginning or at the end. Am I right?

GSAI: You are right about the paint, and mostly right about reflow—with one major caveat called "layout thrashing."

Your understanding of JavaScript's run-to-completion model on the main thread is spot on:

1. Repaint (Painting Pixels)

Because JavaScript and the browser's rendering pipeline share the same main thread, the browser never repaints the screen mid-script. Whether you attach <ul> at the beginning or at the end, the user only sees a single paint after your <script> finishes executing.

2. Reflow (Layout Calculation) & Batching

Modern browsers are also smart about batching DOM mutations:

  • If you only write to the DOM (like appending elements in a loop without reading dimensions), the browser queues those changes and performs one single reflow after your script finishes.
  • The Catch (Forced Synchronous Layout / Layout Thrashing): If ul is already attached to the live document and anything in your loop (or a helper function/library called inside the loop) reads a layout property—such as offsetHeight, clientWidth, or getComputedStyle()—the browser is forced to flush the queue and recalculate layout immediately on every single iteration.

Why Building Detached Is Still the Gold Standard

  • Immune to Layout Thrashing: Modifying a detached DOM tree in memory never triggers live document layout recalculations, even if layout properties are queried elsewhere.
  • No Dirty-Tree Tracking Overhead: When mutating an attached DOM node, the browser still has to mark ancestor nodes as "dirty" for the upcoming layout pass on every .append() call. Building detached skips that overhead until the single final insertion.
  • Cleaner Separation of Concerns: Returning a self-contained DOM node (createUL(data)) makes the builder function reusable and easy to unit-test without needing a live #container in the document.

So for your exact script (pure DOM writes, no layout reads), attaching at the beginning vs. at the end produces the exact same single reflow and single paint—but building detached first is a great habit that protects you as soon as code grows more complex!

Create calendar exercise: Variable name length conventions; combining assignment and increment (++) is discouraged; using inner function and closure for more readable code

20 Nov 2026

(This exchange with Google Search AI is related to my solution of JavaScript.info Create a calendar exercise. Related file in private repo is create-calendar-ex-2.html in modifying-document folder. create-calendar-ex.html is an earlier version of that file.)

Me: I am coding an html page with JS script. I want a variable name for the day of the week for the first day of the month. Is dayOfWeekForFirstOfMonth a good name?

GSAI: dayOfWeekForFirstOfMonth is accurate and completely unambiguous, though firstDayOfWeek or startWeekday is cleaner to type and read in JavaScript.

While your proposed name leaves zero doubt about what the variable holds, long variable names can make calendar math harder to read. Because JavaScript's built-in Date.prototype.getDay() returns an index from 0 (Sunday) to 6 (Saturday), naming your variable around "weekday" or "index" helps prevent confusion with getDate() (which returns 1–31).

...

Me: Yes, it is long and while long names were encouraged in early 2000s C++ world, nowadays in JS I think such long names are not encouraged. And I do see the point that it will make the code having math with this long variable name harder to read. .... So I think firstWeekday is a good name with first being implicitly understood as first of month from the program context. Ur view pl.

GSAI: Yes, firstWeekday is a great choice, and your reasoning is spot on.

Modern JavaScript favors concise, scannable names that rely on surrounding context rather than verbose, self-contained sentences. When you are inside a month-rendering function, first naturally implies "first of the month," and weekday cleanly separates it from the numerical date (1).

Why firstWeekday Works So Well Here

  • Pairs naturally with sibling variables: It creates a clean, predictable naming pattern if you need other month boundaries later, such as lastWeekday or daysInMonth.
  • Keeps math readable: Expressions like (day + firstWeekday) % 7 stay compact and easy to scan at a glance.
  • Avoids JS Date traps: Because JavaScript uses .getDate() for the day of the month and .getDay() for the day of the week, avoiding the generic word day in your variable name prevents subtle mental mix-ups.

...

Me: the loc: (slightly modified later on)

      const firstWeekday = dt.getDay(); // Sunday - Saturday : 0 - 6

BTW was my statement about early 2000s C++ industry conventions favouring long names where required, correct? I ask as it was quite some time back and so I may not (have) recalled correctly.

GSAI: Your memory is spot on—and your line of code looks super clean. ...

Your C++ Memory is Accurate

Your recollection of early 2000s C++ conventions is right on the money. Several overlapping forces pushed C++ developers toward long, explicit variable names during that era:

  • The "Self-Documenting Code" Movement: Books like Steve McConnell's Code Complete (1993, heavily updated in 2004) explicitly pushed back against 1980s/90s cryptic abbreviations (like dOfWk1stMth) in favor of full, descriptive English words.
  • No Modern Autocomplete or Type Hints: Early 2000s IDEs (like Visual Studio 6 or basic text editors) lacked the instant hover-over type inspection and smart IntelliSense we have today. Packing full context into a variable name was a survival strategy when reading a 2,000-line .cpp file.
  • C++ Complexity & Hungarian Notation: C++ codebases frequently mixed raw pointers, references, member variables (m_), and global scopes (g_). Combining scope prefixes, type hints, and full descriptions naturally produced long identifiers.
  • Java's Heavy Influence: Enterprise Java was booming in the early 2000s and popularized notoriously verbose naming patterns (AbstractSingletonProxyFactoryBean style), which spilled over into enterprise C++ shops.

Why Modern JS Shifted Away

Modern JavaScript (especially post-ES6) favors small functions and tight lexical scopes. Because a function today is usually 10–20 lines rather than 200, your eyes can see where dt was created just two lines above firstWeekday, making the extra words unnecessary noise.

...

Me: Excellent explanation. What would you say is the typical max acceptable length for a variable name in modern JS?

GSAI: In modern JavaScript, there is no strict character cap, though most developers aim for 1 to 3 words (roughly 8 to 20 characters) for local variables.

Rather than counting characters, modern JS style guides (like Airbnb’s and Google’s) judge variable length by scope size and line wrapping (most formatters like Prettier wrap lines at 80–100 characters).

Practical Guidelines by Scope

  • Tiny scopes (loops, callbacks, .map()): 1 to 8 characters (i, dt, el, item, user). When the declaration and usage are 2 lines apart, short names keep the logic scannable.
  • Standard local variables (inside a function): 10 to 20 characters / 2–3 words (firstWeekday, daysInMonth, isLeapYear). This is the sweet spot—descriptive enough to read without effort, short enough to fit cleanly in math or conditionals.
  • Module-level constants or config flags: 20 to 30+ characters (MAX_VISIBLE_CALENDAR_WEEKS, defaultLocaleOptions). Because these live far away from where they are used, longer names are still encouraged.

When a Name Is "Too Long"

In modern JS, a name crosses the line when:

  • It forces Prettier to wrap simple lines: If an if statement or basic calculation breaks across 3 lines just because of variable names, they are too long.
  • It repeats context already obvious from the function name: Inside renderMonthCalendar(), firstWeekday is great; calendarMonthFirstWeekday is redundant.

Me: In the same web page, I have nextDay variable which is actually nextDayOfMonth (so day of date instead of day of week). While the script element code is short - around 50 lines involving 3 functions - my early 2000s C++ experience is making me lean towards nextDayOfMonth to clearly differentiate from firstWeekday variable where day is day of week. What would modern JS app coding conventions say?

GSAI: Modern JS conventions would side with your C++ instinct here—use nextDayOfMonth (or nextDate) rather than a bare nextDay.

Even in a 50-line script, modern JS prioritizes disambiguation when two similar concepts live side-by-side. Whenever a file tracks both "day of week" (0–6) and "day of month" (1–31), leaving Day unqualified is widely considered a bug magnet—especially because JavaScript's own Date API already blurs those words (getDay() vs. getDate()).

How Modern JS Developers Would Handle This

1. Keep nextDayOfMonth (14 characters):

At 14 characters, nextDayOfMonth sits right in the modern JS sweet spot (10–20 characters). It isn't overly verbose, and it makes the contrast with firstWeekday crystal clear at a glance.

2. Alternative: Lean into Date vs. Weekday:

Many modern JS developers separate the two concepts completely by reserving weekday for 0–6 and date (or dayNum) for 1–31:

  • firstWeekday (0–6)
  • nextDate or nextDayNum (1–31)

Which One to Pick?

  • Stick with nextDayOfMonth if Date might be confused with a full new Date() object elsewhere in your 50 lines (like dt).
  • Use nextDate only if your Date objects are clearly named things like dt or firstOfMonth.

Your early 2000s C++ instinct served you well here: short names are great until two sibling concepts share the same root word (day), at which point explicit qualification wins in every era of programming.

...

Me: I will use nextDayOfMonth. The code also has date variable (dt) created from new Date. (I used dt as it is local to two consecutive lines of code which I am choosing to keep as two lines instead of one line without dt variable for readability.) So this approach differentiates weekday, day of month and date variables by variable name itself.

GSAI: That is a textbook clean naming system.

By mapping each concept to a distinct naming pattern, you've eliminated the most common source of bugs in JavaScript calendar logic:

  • dt → Full Date object (kept short because its lifespan is just two consecutive lines)
  • firstWeekday → Day of the week (0–6)
  • nextDayOfMonth → Day of the month (1–31)

Keeping dt on its own line rather than chaining new Date(...).getDay() is also great modern JS practice. Splitting creation and extraction onto two lines makes the code much easier to scan and debug if you ever inspect the values in browser DevTools.

...

Me:

    daySlot = nextDay;
    nextDay++;
    // daySlot = nextDay++;

In early 2000s C++ program I would have opted for commented line (single line).

In modern JS, I am not sure and so opted for 2 separate lines. What would modern JS conventions recommend?

GSAI: Modern JS conventions strongly favor your two-line approach over the single-line postfix increment (daySlot = nextDay++).

Major JavaScript style guides—including Airbnb, Google, and StandardJS—explicitly discourage combining assignment and increment (++) on the same line. In fact, ESLint has a widely used built-in rule (no-plusplus) specifically designed to prevent subtle bugs caused by ++ expressions.

Why Modern JS Prefers Two Separate Lines

  • Eliminates mental parsing: With daySlot = nextDay++, the reader has to pause and verify whether daySlot gets the value before or after the increment (postfix vs. prefix). Two separate lines remove all ambiguity.
  • Prevents accidental off-by-one bugs: If someone later refactors or reorders lines, splitting assignment from mutation makes it much harder to accidentally break the counter.
  • Cleaner diffs in version control: Keeping each state change on its own line makes Git diffs easier to read when reviewing changes.

...

(Note: Many strict JS linters like Airbnb even prefer nextDayOfMonth += 1 over nextDayOfMonth++, though standalone nextDayOfMonth++; on its own line is completely fine and widely used in everyday JS.)

(I then did a few code review rounds of the file with GSAI. Some points from it:)

Me: Here's the full code of the page which is a Javascript.info exercise solution I did. Pls review code

---snipped---

GSAI: Your solution is clean, accurate, and handles all the calendar math without needing the extra date-mutating loop used in the official JavaScript.info solution.

Using new Date(year, month, 0).getDate() to grab the total days in the month up front makes your row-building logic much simpler and easier to follow than mutating a Date object day-by-day.

What Works Really Well

  • Smart Monday-offset math: let numStartBlankTDs = firstWeekday ? firstWeekday - 1 : 6; is concise and cleanly converts Sunday (0) to 6 leading blank cells while shifting Monday (1) through Saturday (6) to 0–5.
  • Automatic trailing blank cells: Because your for (let i = 0; i < 7; i++) loop always runs 7 times per row, it automatically pads the final week with empty <td></td> cells to keep the table square—fulfilling step 5 of the problem requirements without needing a second cleanup loop.
  • Single DOM insertion: Building the HTML string in memory and calling elem.insertAdjacentHTML('beforeend', html) once at the end avoids repeated DOM reflows.

Minor Improvements to Consider

...

Remove the redundant guard inside createMonthRow():

Because your outer while (nextDay <= daysInMonth) loop already guarantees nextDay <= daysInMonth before calling createMonthRow(), the first line inside createMonthRow() (if (nextDay > daysInMonth) return '';) can never be reached and can be safely removed.

...

Me: ... About redundant guard in createMonthRow() - In early 2000s C++ (Over past 2 to 3 years, I am in process of getting back to industry sw dev after a gap of over 20 years), I would prefer having this extra guard for easier reusability. It does not cost much and may be valuable when reused perhaps as copy-paste but with function calling code not having the guard.

GSAI: Defensive programming like that is a great habit—especially when you're thinking ahead to reusability.

Why Your Guard Clause Makes Total Sense

  • Defensive Programming / Design by Contract: Making createMonthRow() self-protecting (if (nextDayOfMonth > daysInMonth) return '';) ensures the function never produces an all-blank <tr> row, even if a future caller forgets to check the boundary first.
  • Zero Practical Cost: In modern V8/SpiderMonkey JS engines, an integer comparison costs practically nothing, and a single early-return line actually makes the function's precondition immediately obvious to anyone reading it later.
  • Modern JS Still Loves Guard Clauses: In fact, "early return" guard clauses at the top of functions are heavily promoted in modern JS clean-code guides to avoid deeply nested if/else blocks.

The only caveat modern JS tools might flag is code coverage: if you ever run automated unit tests with a coverage tool (like Jest or Vitest), it would mark that return ''; branch as "uncovered" unless a test calls createMonthRow() directly out of bounds. For application and utility code, though, keeping the guard is completely solid engineering.

...

Me: ... Now about my usage of inner createMonthRow() function in createMonthRows(). This is something I am having to learn as in early 2000s C++ we did not have such inner functions and closures, IIRC.

Have I used JavaScript inner function and closure (accessing outer function variables from inner function - createMonthRow()) as per modern JS conventions? Note that in an early 2000s C++ mindset, I would have had two individual functions, and passed additional parameters to createMonthRow() from createMonthRows() and had a return object instead of return primitive, if I needed to return more than one primitive. In JS, I am able to avoid all that using outer and inner functions.

GSAI: Yes—you nailed one of JavaScript's core strengths, and your instincts here are spot on.

In early 2000s C++ (pre-C++11 lambdas), simulating this required either passing five state variables by reference (int& nextDayOfMonth, int& numStartBlankTDs...), creating a helper struct, or writing a small private class just to hold shared state across two methods. In JavaScript, a nested function with a closure solves that exact problem with zero boilerplate.

Why Your Closure Usage Fits Modern JS Conventions

  • Encapsulating shared mutable state: numStartBlankTDs and nextDayOfMonth are mutated across multiple row calls. Keeping createMonthRow() nested inside createMonthRows() keeps that mutable state completely private to the outer function—nothing outside createMonthRows() can accidentally touch or corrupt it.
  • Eliminating parameter clutter: You avoided passing daysInMonth, numStartBlankTDs, and nextDayOfMonth back and forth or packing them into a return object.
  • Clear helper scoping: Because createMonthRow() only makes sense inside createMonthRows(), nesting it signals to future readers that it is a local helper, not a general-purpose utility.

One Small Tension to Watch (Reusability vs. Closure)

Earlier, you mentioned adding the guard clause in case createMonthRow() is copy-pasted/reused elsewhere. Keep in mind that closures trade standalone reusability for convenience:

  • As a nested closure, createMonthRow() is tightly coupled to the outer variables (nextDayOfMonth, daysInMonth, numStartBlankTDs). You couldn't simply move it to the top level without converting those captured variables into parameters.
  • In modern JS, that trade-off is completely fine—developers prefer clean closures for local helpers and only extract top-level pure functions (with explicit parameters) when they actually need to reuse the function in multiple places.

Modern C++ Side Note

Interestingly, modern C++ (C++11 and later) eventually adopted this exact pattern via lambdas with capture clauses ([&]() { ... }), which work almost identically to your nested JS closure!

...

Me: Great response. Yes, reusability of inner function is impacted. Noted.

I also could have implemented the inner function as code in the while loop of the outer function itself. But that would mean more indented code and harder to read than having an inner function of createMonthRow(). Do you agree?

GSAI: I completely agree—extracting createMonthRow() as an inner function makes the code significantly cleaner and easier to read.

In modern JavaScript (and clean code principles in general), deeply nested loops inside loops are a classic readability trap.

Why Your Inner Function Wins Over a Nested Loop

  • Flattens indentation: Putting the for loop inside the while loop creates 4–5 levels of indentation (function → while → for → if/else if). Separating them keeps indentation shallow and easy on the eyes.
  • Separates what from how: Your while loop reads almost like plain English:
while (nextDayOfMonth <= daysInMonth) {
  htmlRows += createMonthRow();
}

Anyone reading createMonthRows() immediately sees the high-level flow without getting bogged down in <tr> and <td> string-building details.

  • Zero performance downside: Modern JS engines inline small, frequently called local functions like createMonthRow() automatically, so you get the readability of modular code with the speed of a flat loop.

Your instinct to break complex loop bodies into a small, well-named local helper is textbook modern JS design.

Gem review of my create calendar solution; Gem comparison of my solution vs Javascript.info provided solution

(Switched back to Gemini chat: JavaScript-Refresher-P13-20261112)

Me: 20 Nov. Uploaded file (create-calendar-ex-2.html) is my solution to last discussed Javascript.info exercise: https://javascript.info/modifying-document#create-a-calendar. It produces output as expected. Please review it.

Gem: Your solution is logically solid, handles the calendar arithmetic cleanly, and avoids the common pitfalls of this exercise. Every edge case—including leap years, 4-to-6 week months, and trailing blank cells—works accurately.

What Works Well

  • Smart Date Arithmetic: Using new Date(year, month, 0).getDate() to get the exact number of days in the month is an idiomatic, clean trick that automatically handles 28/29/30/31-day months and leap years.

  • Unified 7-Day Row Loop: By always iterating i from 0 to 6 inside createMonthRow(), your code handles leading blanks, valid day numbers, and trailing blanks in a single unified pass without needing a separate cleanup loop for the final week.

  • Non-Destructive Insertion: Using elem.insertAdjacentHTML('beforeend', html) lets you render both the November 2026 and September 2012 calendars into the same container without wiping out or re-parsing the first table.

  • Readability Discipline: Splitting daySlot = nextDayOfMonth; and nextDayOfMonth++; onto separate lines rather than embedding the increment inside the assignment is cleaner and aligns well with modern JS linting standards.

  • Strict Mode & JSDoc: Including 'use strict'; at the top of the script and typing elem with @param {HTMLElement} are great habits.


Points to Refine for Production Standards

...

  • Semantic Table Markup: Wrapping the header row in <thead>...</thead> and the date rows in <tbody>...</tbody> produces cleaner semantic HTML (browsers implicitly insert a <tbody> anyway, which can cause subtle surprises if you later inspect table.firstChild in the DOM). Similarly, using a <caption> inside the <table> for the year/month heading ties the title directly to the table for screen readers, rather than placing an <h2> after </table>.

...

  • Append vs. Replace Behavior: Using insertAdjacentHTML('beforeend', ...) works well for displaying multiple test calendars in one <div>. If this function were used in an interactive month-picker where calling createCalendar() should replace the previous month, you would clear elem first (e.g., elem.textContent = '';) or assign directly to elem.innerHTML.

...

Me: Now can you compare my solution uploaded earlier with solution provided by javascript.info - https://javascript.info/modifying-document#create-a-calendar ...

Gem: Both solutions take the HTML-string approach, but yours is structurally cleaner and actually avoids an edge-case bug present in the javascript.info solution.

Side-by-Side Comparison

Aspect Your Solution (create-calendar-ex-2.html) javascript.info Solution
Date Handling Computes daysInMonth once upfront (new Date(year, month, 0).getDate()) and loops with plain integers. Mutates a Date object on every day (d.setDate(d.getDate() + 1)) and loops while (d.getMonth() == mon).
Row Construction Row-centric: createMonthRow() always opens and closes a complete 7-cell <tr>...</tr>. Stream-centric: uses 3 separate loops (leading blanks, days, trailing blanks) and splices </tr><tr> mid-loop whenever Sunday is hit.
Weekday Offset Calculated once upfront via ternary (firstWeekday ? firstWeekday - 1 : 6). Extracted into a reusable getDay(date) helper (0 = Mon ... 6 = Sun), called repeatedly during iteration.
DOM Insertion elem.insertAdjacentHTML('beforeend', html) (appends). elem.innerHTML = table (replaces).
Code Style 'use strict', const/let, template literals. Loose equality (==, !=), + string concatenation.

Key Architectural Differences

  • No Empty Trailing <tr></tr> Bug: This is the biggest win for your design. In javascript.info, the loop checks if (getDay(d) % 7 == 6) (Sunday) and immediately appends '</tr><tr>'. If the last day of the month happens to be a Sunday (for example, May 2026 or August 2026), it opens a brand-new <tr> right before the loop ends, and then closes the table with '</tr></table>', leaving an empty <tr></tr> at the bottom of the DOM. Because your createMonthRow() always builds a self-contained row and checks while (nextDayOfMonth <= daysInMonth) before starting another, your HTML is always cleanly balanced.

  • Integer Loop vs. Mutating Date: Calculating daysInMonth once and counting 1..daysInMonth is faster, easier to reason about, and avoids repeatedly mutating a Date object just to detect when the month rolls over.

  • Single Unified Loop vs. Three Phases: The javascript.info solution splits the grid into three separate loops (leading blanks, days, trailing blanks). Folding all three states into one 7-iteration row loop makes your rendering logic much easier to verify at a glance.

  • Minor Quirks in javascript.info: The tutorial uses getDay(d) % 7 == 6, where % 7 is redundant since its getDay() helper already returns 0..6. It also uses loose equality (== / !=) instead of strict equality (=== / !==).

  • Where javascript.info Has an Edge: Extracting getDay(date) as a standalone, pure helper function is clean if you ever need Monday-first weekday logic elsewhere. Also, elem.innerHTML = table strictly matches a "render this month into elem" contract, whereas insertAdjacentHTML('beforeend', ...) appends—which was intentional for your two-calendar test, though you'd clear elem first for a single-calendar widget.

Overall, your solution is more robust and closer to production-grade vanilla JS than the official tutorial solution. Would you like to try the in-memory DOM node refactor (createElement) next, or move on to DocumentFragment / CSS classes and styles?

Whitespace between inline/inline-block elements (like span and input) creates text nodes that impact layout outside of Flex/Grid CSS; Chrome DevTools hides those text nodes

21 Nov 2026

Next I looked at: Colored clock with setInterval Javascript.info exercise. I encountered an issue of space between span elements due to white space between them in the source code. I had not faced that in ReactJS apps and so could not figure out the issue till Gemini explained it. Related exchange snippets are given below.

Me: In following fragment, I expected no space between hh and :. But there is a gap. Chrome Inspect shows margin and padding to be 0. From where is this gap coming?

<head>
  <style>
    #hh {
      color: red;
    }

    #mm {
      color: green;
    }

    #ss {
      color: black;
    }
  </style>  
</head>
<body>
<div>
  <span id="hh">hh</span>
  <span>:</span>
  <span id="mm">mm</span>
  <span>:</span>
  <span id="ss">ss</span>
</div>

Gem: The gap comes from the newlines and indentation between the <span> tags in your HTML source code.

Here is what happens under the hood:

  1. DOM Parsing: Just like the invisible whitespace nodes between <li> tags, the browser parses the newline and spaces between </span> and <span> into a Text node in the DOM. (If you inspect document.querySelector('div').childNodes in the DevTools console, you will see #text nodes sitting between every <span>.)
  2. Inline Rendering: Because <span> elements are display: inline by default, the browser lays them out like words in a sentence. Under the default CSS white-space: normal rule, any sequence of whitespace characters (newlines, tabs, spaces) between inline elements is collapsed into a single visible space character.
  3. Why DevTools Shows 0 Margin/Padding: That space does not belong to the CSS box model of any <span>—it is a literal rendered text character sitting between them.

How to Remove the Gap

1. Remove the whitespace in HTML (simplest for a clock): Put the tags directly next to each other with no spaces or newlines between them. If the colons don't need their own styling, you don't even need <span> wrappers around them:

<div>
  <span id="hh">hh</span>:<span id="mm">mm</span>:<span id="ss">ss</span>
</div>

2. Use Flexbox on the parent <div> (keeps multi-line HTML readable):

div {
  display: flex; /* or inline-flex */
}

Flex containers ignore whitespace-only Text nodes between their child items, eliminating the gap automatically without forcing you to cram all the tags onto a single line.

Me: 21 Nov. The HTML you suggested fixed it. Hmm. I had not realized this impact. And Chrome inspect by default swallows up the text nodes. So unless I use DOM code to check child nodes, I can't catch the cause. Am I right?

Gem: You are right—Chrome DevTools' Elements panel intentionally hides whitespace-only #text nodes to keep the DOM tree readable, and it does not offer a setting to turn them on. Even though those nodes are actively sitting in memory and affecting inline layout, the Elements panel renders the tree as if they aren't there.

That said, you don't necessarily have to write script code to catch them. A few quick ways to spot this in the future:

  • Drag-select on the rendered page: Try highlighting hh : mm with your mouse directly on the page. Because the gap is a literal space character rather than CSS margin or padding, you will be able to highlight the blank space between hh and :. That is usually the fastest visual giveaway.
  • Inspect via $0.childNodes in the Console: Click the parent <div> in the Elements panel, switch to the Console, and run $0.childNodes. Unlike the Elements panel, the Console prints the raw, unfiltered NodeList, immediately exposing the #text nodes sitting between every <span>.
  • Firefox DevTools (for comparison): Unlike Chrome, Firefox's Inspector explicitly displays a small whitespace badge directly in the DOM tree for whitespace-only text nodes, making this exact layout issue visible at a glance.

Once you get bitten by this quirk once, it becomes easy to recognize: whenever inline elements have an unexplained ~4px gap despite having 0 margin and 0 padding, HTML source whitespace is almost always the culprit.

Me: The blank space between spans does NOT get highlighted even when "Select an element in the page" option of DevTools is used. That's what I tried first. Next I checked padding and margins. ...

$0.childNodes is what I meant by DOM coding.

So looks like Chrome DevTools forces you to use DOM coding to get the blank text nodes.

Gem: Yes, your conclusion is spot on. In Chrome DevTools, there is no visual UI in the Elements panel to inspect whitespace-only #text nodes—you are forced to drop into the Console and query the DOM directly with $0.childNodes.

The "Select an element in the page" picker (Ctrl+Shift+C) only targets Element nodes, never Text nodes. When you hover over the gap between two <span>s, the picker simply falls through to the parent <div>, leaving you staring at 0 margin and 0 padding with no visual clue in the inspector.

(One quick clarification on my earlier "drag-select" tip: I meant ordinary text selection on the webpage itself—dragging the mouse across hh : mm as if you were copying text to the clipboard. The browser's blue text-selection highlight will fill in the gap between hh and :, whereas CSS margin or padding is never selectable as text. That gives you a fast hint that a literal space character is there, though it doesn't show you the node in DevTools.)

It is a genuine blind spot in Chrome's Elements panel compared to Firefox's Inspector. In Chrome, checking $0.childNodes in the Console is the only way to actually see those whitespace nodes in the tree.

Me: Understood drag-select. yes, with drag-select, I can specifically extend the selection to include that text-node whitespace. Got it.

Drag-select shows me a blank space between the two input buttons as well, for perhaps the same reason. Am I right?

Gem: Yes, it is the exact same mechanism.

<input> elements (as well as <button> and <img>) default to display: inline-block, which means they participate in the same inline formatting context as <span> and plain text. Because they sit on a text baseline like words in a sentence, any newline or indentation between two <input> tags in your HTML source collapses into a single visible space character—which is why drag-select picks it up.

With buttons, this accidental gap often goes unnoticed because a little separation looks natural. It only becomes a nuisance when you want exact spacing: if you add margin-right: 10px to the first button, you actually end up with 10px plus the width of that hidden space character (~4px). Wrapping the buttons in a display: flex container and using the CSS gap property eliminates the phantom text space and gives you exact control over the spacing.

Me: Do these gaps get cancelled by some top-level CSS directives? In standard React apps that I read, which heavily use flex, I never had to worry about this whitespace getting converted to text nodes and taking up tiny bits of screen. Or maybe I simply missed it completely!

Gem: No—top-level CSS resets do not cancel these gaps, and you didn't miss them in React apps either. You never ran into this in React because of two distinct shields working in your favor: JSX strips formatting whitespace at compile time, and Flexbox/Grid containers ignore whitespace-only text nodes.

  • Why top-level CSS resets don't fix it: Standard CSS resets (margin: 0; padding: 0;) and Tailwind's Preflight only normalize box-model properties. They cannot globally disable space characters in inline formatting without breaking normal text across the entire page. (Before Flexbox existed, developers actually resorted to an ugly CSS hack—setting font-size: 0 on the parent container and then restoring font-size: 16px on the children—just to collapse that phantom space to 0 pixels.)
  • JSX strips newlines between tags: In raw HTML, the browser's HTML parser turns indentation and newlines between <span> tags into #text nodes. In React, JSX is compiled into JavaScript function calls before it ever reaches the browser, and the JSX compiler deliberately strips whitespace and newlines between adjacent tags. This JSX:
<div>
  <span>hh</span>
  <span>:</span>
  <span>mm</span>
</div>

compiles down to three direct <span> children with no text nodes in between. In fact, React developers face the exact opposite quirk: if you want a space between two inline tags on separate lines in JSX, you have to explicitly write {' '}.

  • Flexbox and Grid ignore whitespace nodes: Even in raw HTML where whitespace #text nodes do exist in the DOM, the CSS Flexbox and Grid specifications explicitly state that whitespace-only text nodes between child items are ignored during layout—they do not generate flex/grid items and take up zero space. Because modern React apps use display: flex and display: grid for almost all component layouts, spacing is controlled cleanly via CSS gap instead.

So this phantom gap is primarily a raw-HTML + inline-layout quirk that modern frameworks and Flexbox largely insulate you from.

Me: Terrific explanation. I was wondering how I did not encounter this whitespace issue in past 2 years or so where, off and on, I have read and written fair bit of React JS/Next Js code. Even in vanilla JS code, I have used flex heavily. In this case, I am doing a Javascript.info exercise whose skeleton code is minimal HTML and so I am following that style. ... Your above explanation resolves my 'wondering' completely. Hmm. Web dev world sure has lot of quirks and surprises lurking around every corner.

...

Me: I used Console to list childNodes of the div. It shows the text node after span having this attribute:

data: "\n  "

The VS Code source has \n followed by perhaps a tab. Now in the rendered HTML it seems to have a single space for above two characters of \n and space. What are the rules for text node rendering in HTML, for characters like \n, \t etc.

Gem: The HTML parser preserves those raw whitespace characters in the DOM (data: "\n "—which is a newline plus two spaces, since VS Code converts Tab presses to spaces by default; a literal tab would show as "\n\t"). The actual collapsing happens later in the CSS layout engine, governed by the CSS white-space property (which defaults to normal).

Under the default white-space: normal rule, the rendering engine applies four steps to standard ASCII whitespace characters—space ( ), tab (\t), and newline (\n):

  1. Normalization: Every \t and \n is treated as an ordinary space character.
  2. Collapsing: Any contiguous sequence of spaces, tabs, and newlines collapses into a single space. Whether your source has "\n ", "\n\t\t ", or twenty spaces in a row, it renders as one space.
  3. Line-Edge Trimming: Leading whitespace immediately after an opening block tag (<div>\n <span>) and trailing whitespace immediately before a closing block tag (</span>\n</div>) are stripped completely during layout. That is why the "\n " before <span id="hh"> and after <span id="ss"> took up 0px, while the identical "\n " between the <span> tags collapsed into a visible space.
  4. Block vs. Inline Context: Whitespace-only text nodes sitting between block-level elements (like two <div>s or two <li>s) are ignored during layout and take up 0px. They only become a visible single space when sitting between inline or inline-block elements (<span>, <a>, <input>, <button>, <img>) inside an inline formatting context.

(One notable exception: a non-breaking space—&nbsp; or \u00A0—is intentionally excluded from these rules and is never collapsed or trimmed.)

Overriding These Rules with CSS white-space

If you want the browser to treat \n, \t, or multiple spaces differently, you control it via the CSS white-space property on the element:

white-space value Spaces & Tabs ( , \t) Newlines (\n) Automatic Line Wrapping
normal (default) Collapsed to 1 space Converted to space & collapsed Yes
nowrap Collapsed to 1 space Converted to space & collapsed No (overflows horizontally)
pre (used by <pre>) Preserved literally Preserved as line breaks No
pre-wrap Preserved literally Preserved as line breaks Yes
pre-line Collapsed to 1 space Preserved as line breaks Yes

In practice, white-space: pre-wrap and white-space: pre-line are especially useful in Vanilla JS apps: they let you safely assign multi-line user text via elem.textContent (avoiding innerHTML and <br> tag injection) while still honoring the user's line breaks.

In React/Next.js, JSX strips indentation and new lines between adjacent tags; Flex and Grid CSS ignore such whitespace; Exception cases in React/Next.js/Tailwind where CSS white-space rules still apply

Me: pre for showing code indentation is something I have seen and used. ... Noted the collapse to single space rule and had quick look at other rules. Hmm. Quite intricate. But in React JS/ Next JS/ Tailwind world, all of these quirks typically don't come into play - correct?

Gem: Mostly yes for layout gaps between elements, but no for text content—the browser's CSS white-space engine still governs every text node React renders.

Where React / Next.js / Tailwind shields you:

  • No phantom gaps between tags: Because JSX strips indentation and newlines between adjacent tags at compile time, those stray "\n " text nodes are never created in the DOM.
  • Flex and Grid by default: Modern Tailwind layouts rely heavily on flex or grid with gap-* utilities, which explicitly ignore whitespace-only text nodes between child elements.

Where these exact rules still show up in React / Next.js / Tailwind:

  • Multi-line text from data or <textarea>: If you render {userComment} containing \n line breaks, CSS white-space: normal still collapses every newline into a single space. You have to add Tailwind's whitespace-pre-wrap or whitespace-pre-line class to preserve them.
  • Preventing line wraps in UI controls: Buttons, badges, and table headers still wrap on spaces by default, which is why Tailwind's whitespace-nowrap (and truncate, which combines whitespace-nowrap, overflow-hidden, and text-ellipsis) gets used constantly.
  • The opposite JSX quirk (missing spaces): Because JSX aggressively strips newlines between inline elements, formatting text and inline tags across multiple lines can occasionally mash words together (<span>Hello</span> followed on the next line by <span>World</span> renders as HelloWorld). In those cases, you end up explicitly inserting {' '} to force a space.

So while you almost never trip over the accidental inline-tag gap in React/Tailwind, the underlying CSS white-space collapsing rules are still very much active whenever you deal with dynamic text.

Would have been nice if Chrome DevTools showed visual indicator when whitespace-only text nodes were impacting layout

Me: Regarding Chrome DevTools showing the text content, my point is that it need not do it for all elements. But when one is inspecting elements, point and click kind of thing, that's when, or at least in places where the text content is affecting the layout, that's where my expectation as a developer is that Chrome DevTools should show me that look, this is where text content is impacting the layout. And it can be a very subtle visual element, like you said Firefox DevTools does.

Gem: That distinction—surfacing whitespace only when it actually affects layout—completely solves the "tree clutter" objection.

Under the hood, Chrome's Blink layout engine already knows the difference. It knows that the "\n " sitting between two <div> tags was discarded during layout (0px), while the "\n " sitting between two <span> or <input> tags generated a real inline box occupying ~4px of screen width. Showing a subtle highlight in the element picker when you hover over that gap, or a muted badge in the Elements tree strictly for layout-impacting text nodes, wouldn't bloat the DOM view at all.

It stands out even more because Chrome DevTools has invested heavily in visual layout overlays for everything else—margins, paddings, Flexbox gaps, and Grid tracks all light up clearly on hover. Leaving inline whitespace completely invisible creates a blind spot right where a developer naturally looks first. Firefox DevTools proved the concept works well by showing a compact whitespace indicator in the tree with a tooltip explaining its role, so expecting Chrome to offer at least a subtle layout cue on inspect is completely reasonable. ...

Colored clock with setInterval Javascript.info exercise solutions - Gemini review

Me: https://javascript.info/modifying-document#colored-clock-with-setinterval exercise has a provided solution .

Uploaded file (colored-clock-ex-2.html in modifying-document folder in private repo) is my solution. Please compare and comment.

Gem: Your solution in colored-clock-ex-2.html is cleaner and more modern than the javascript.info solution in several key areas—particularly in how you format numbers, target elements, and update the DOM.

Side-by-Side Comparison

Aspect Your Solution (colored-clock-ex-2.html) javascript.info Solution
DOM Updating Uses .textContent. Uses .innerHTML.
Element Targeting Explicit IDs (#hh, #mm, #ss) via querySelector. Positional indices (clock.children[0], [1], [2]).
Zero-Padding Modern .toString().padStart(2, '0'). Manual if (hours < 10) hours = '0' + hours;.
Start Guard Checks if (!intervalTimerId) to prevent duplicate timers. Checks if (!timerId) to prevent duplicate timers.
Immediate Render Calls renderCurrentTime() right away on start. Calls update() right away on start.
Resetting Timer ID intervalTimerId = undefined;. timerId = null;.

Where Your Solution Wins

  • textContent over innerHTML: Assigning formatted numbers via .textContent bypasses the browser's HTML parser and follows modern DOM best practices, whereas the tutorial falls back on .innerHTML.

  • Resilient Selectors: Targeting #hh, #mm, and #ss directly is much safer than clock.children[0..2]. Positional indexing is brittle—if someone wraps the colons in <span>:</span> (as your HTML does), children[1] would suddenly point to a colon instead of the minutes.

  • Idiomatic Formatting: Using .toString().padStart(2, '0') is concise, declarative, and eliminates three repetitive if (< 10) branches.

(Gem also suggested some refinements, most of which I implemented.)

Me: good review. ... (About Gem refinement: ... 'Calling clearInterval(undefined) or clearInterval(null) is a guaranteed no-op per the HTML specification'. Gem implied that I don't need to check for id not being undefined/null and calling clearInterval with id only in that case.) https://developer.mozilla.org/en-US/docs/Web/API/Window/clearInterval only says: "If the parameter provided does not identify a previously established action, this method does nothing." ... It does not establish a norm that it is OK to call it with null/undefined.

In early 2000s C++ world, you simply avoid calling a function with an invalid parameter. I am finding it hard to embrace JS style of brevity in this case by not checking for invalid parameter before call. I mean, clearInterval() may behave this way, but some other JS runtime functions may not. Your view pl.

Gem: ... Your point about API inconsistency across the JavaScript runtime is completely valid:

  • Forgiving APIs: clearInterval(null) and removeEventListener() with an unknown callback silently do nothing.
  • Strict APIs: parent.removeChild(null), observer.unobserve(null), and JSON.parse(undefined) immediately throw a TypeError or SyntaxError.

Relying on "this specific Web API happens to ignore null" forces you to memorize per-method quirks. It is much like C++ where delete nullptr is guaranteed safe by the standard, yet fclose(NULL) is undefined behavior—guarding teardown calls consistently saves you from stepping on a landmine in the APIs that aren't forgiving.

There is also a modern JS/TypeScript reason that validates your instinct: in TypeScript (and VS Code's // @ts-check JSDoc mode), the official DOM type signature for clearInterval is clearInterval(id?: number): void. If you store null in intervalTimerId and pass it directly without a guard, the type checker actually flags it as an error. ...

When to assign null and when to use default undefined in JavaScript for variables

(This was about when to use undefined and when to use null for ids like intervalTimerId here.)

Me: ... javascript.info (provided solution) - uses undefined as initial value and resets it to null! It works as the test for it is simply !timerId.

...

Me: ... Does MDN itself (JS world and not TS) provide a guidelines on this aspect of undefined vs null for such cases?

Gem: MDN does not prescribe a rigid coding rule for whether you should initialize or reset local variables to null versus undefined. Instead, MDN explains how the JavaScript language itself separates them conceptually, and explicitly acknowledges that individual codebases set their own style rules.

What MDN Officially Says

Across its JavaScript data types and data structures guide and the null reference page, MDN draws three main distinctions:

  • undefined = absence of a value (the language default): MDN notes that JS defaults to undefined whenever something has no value—an uninitialized variable (let x;), a return; with no expression, a missing object property, or core methods like Array.prototype.find() and Map.prototype.get() when nothing is found.
  • null = intentional absence of an object value: MDN defines null specifically as representing the intentional absence of an object (for example, the end of a prototype chain or document.querySelector() returning null when no element matches). It also points out a practical runtime difference: JSON.stringify() preserves null, whereas it omits object properties set to undefined.
  • No universal style mandate: On the null reference page, MDN explicitly remarks that when designing an API, you should usually treat null and undefined as equivalent inputs "because many codebases have stylistic rules about when to use null or undefined by default."

What This Means for Your Plain JS Code

For a local numeric handle like intervalTimerId (which isn't an object and isn't being serialized to JSON), MDN leaves the choice to you:

  • Initializing let intervalTimerId = null; and resetting it to null is a very common plain-JS convention because it makes the "no active timer" state visibly intentional right at the declaration.
  • Leaving let intervalTimerId; uninitialized and resetting it to undefined is equally valid in plain JS, and actually aligns with MDN's note that undefined represents the absence of a non-object value.

In plain JS projects, the only real pitfall is mixing the two in the same variable's lifecycle and then using strict equality (!== null or !== undefined). As long as you stay consistent with whichever one you pick—and follow the house style when working on a team codebase—you are completely aligned with MDN. ...

Me: 22 Nov. MDN: undefined = absence of a value (the language default); null = intentional absence of an object value.

I think the above two points are helpful. I think we could extend it in this fashion:

  1. If a variable is not being reset, then we can let it be initialized as undefined by default.
  2. If a variable is being reset, then as it is an intentional absence, we should set it to null during reset. Further, to keep the variable value consistent, we should initialize it to null (and not initialize it to undefined).

We need not consider TypeScript issues as TS is an optional addon to JS, even in ReactJS/NextJS context. What do you think of this guideline?

Gem: That is a sharp, practical guideline for plain JavaScript—it turns a notoriously fuzzy stylistic debate into a concrete, self-documenting rule.

Here is why it holds up well in real-world Vanilla JS:

  • Eliminates the three-state trap: Rule 2 guarantees a resettable variable only ever holds a valid value or null. Strict checks like if (intervalTimerId !== null) work reliably from the very first line of execution through teardown, without relying on truthy/falsy coercion to paper over an undefined/null mismatch.
  • Keeps undefined owned by the engine: You never have to manually write x = undefined;, which aligns with the long-standing JS convention of letting the runtime handle undefined while your code explicitly manages null.
  • Makes intent obvious at a glance: Seeing let timerId = null; immediately signals "this is a stateful handle that can be empty or cleared." Seeing an uninitialized let result; (in cases where const isn't possible, like assigning inside an if/else or try/catch block) signals "this will be populated shortly and not cleared."
  • Pragmatic fit with MDN: Although MDN historically phrases null as the absence of an object, extending it to resettable primitives—like numeric timer IDs, array indices, or cached strings—is completely standard practice across plain-JS codebases.

There is just one plain-JS quirk worth keeping in mind under Rule 2: default function parameters (function fn(x = 10)) only trigger when the argument is undefined, not when it is null. That will never affect internal handles like intervalTimerId, and only matters if you pass a null-initialized variable into a function expecting a default value to kick in.

Overall, it is a clean, disciplined standard to adopt for your Vanilla JS code. Are you ready to move on to DocumentFragment or CSS styles and classes next, or do you have another exercise from the "Modifying the document" chapter lined up?

Me: Noted the default function parameter quirk but we can live with that. But this approach is not limited to vanilla JS. It can be used in ReactJS/NextJS (apps) too (which are not using TypeScript).

Gem: You are right—in fact, React and Next.js actively reinforce your guideline.

In plain-JS React and Next.js codebases, Rule 2 maps directly onto the framework's standard idioms:

  • useRef(null) for mutable handles: Storing a timer ID or DOM element reference almost universally starts with const timerIdRef = useRef(null); and resets with timerIdRef.current = null;.
  • useState(null) for resettable state: For values that start empty, get populated, and can be cleared later (like const [error, setError] = useState(null); or const [selectedItem, setSelectedItem] = useState(null);), initializing and resetting to null is the standard React convention.
  • Next.js serialization bonus: Because null is valid JSON while undefined is not, using null prevents serialization errors across server-to-client boundaries (such as API responses or Next.js getServerSideProps props).
  • Clean JSX rendering: React treats null as "render nothing," so returning null from a component or rendering {error} when it is null works seamlessly without outputting stray text.

Your two-part guideline carries over cleanly from Vanilla JS straight into React and Next.js. ...

(I made the improvements and did a final review round.)

Gem: This revision is clean, disciplined, and noticeably tighter than the official tutorial solution.

What's Working Well

---snipped---

Three Tiny Nitpicks (Purely Optional)

  • Explicit null comparisons: Because intervalTimerId is now guaranteed to be either null or a positive timer ID, using if (intervalTimerId === null) in clockStart() and if (intervalTimerId !== null) in clockStop() matches your defensive style even more closely than truthy/falsy checks (!intervalTimerId and intervalTimerId).

---snipped---

Me: Interesting nitpicks. ... About 1st - explicit null comparison: I don't want to diverge from JS dev conventions when it is not needed. Javascript.info tutorial using initial value of undefined and reset value of null was odd enough to be avoided. But (!intervalTimerId) seems to be standard JS dev convention .. Note that MDN for setInterval clearly says that valid ids are positive integers. .... So I don't want to check for !== null as guys will think it is a C++ programmer thing and not a JS programmer style.

Gem: That is a very grounded balance between defensive discipline and writing idiomatic JavaScript.

You nailed the exact reason if (!intervalTimerId) and if (intervalTimerId) are standard across JS codebases: because the spec guarantees timer IDs are positive non-zero integers, a valid 0 can never sneak in and trigger a false negative. Any seasoned JS developer reading let intervalTimerId = null; followed by if (!intervalTimerId) will see clean, natural JavaScript—not C++ with a JS accent.

Saving explicit !== null checks for values where 0, "", or false are legitimate states (like array indices, counts, or coordinates) is actually the exact line most experienced JS developers draw. ...


White space around > combinator is optional but recommended; White space only acts as descendant combinator when it separates two selectors with no other combinator symbol (>, +, or ~) between them

Me: 23 Nov .... https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/Child_combinator says: "The white space around the > combinator is optional but recommended."

The problem is that space is also descendant selector. So does that not create confusion?

Gem: For the CSS parser, there is zero ambiguity—and for human readers, those spaces actually make selectors easier to read rather than more confusing.

Why the Parser Never Gets Confused

In the CSS Selectors specification, whitespace only acts as a descendant combinator when it separates two selectors with no other combinator symbol (>, +, or ~) between them. Whenever one of those symbols is present, any surrounding whitespace is simply absorbed as optional padding around that combinator.

Because of that grammar rule, all of these parse identically as a single child combinator:

div>p { ... }
div > p { ... }
div   >   p { ... }

Why MDN and Style Guides Recommend Spaces

  • Visual separation (like operators in code): Just as you write a > b instead of a>b in JavaScript or C++, putting spaces around >, +, and ~ keeps complex selectors scannable—compare .nav-list > .item > a against .nav-list>.item>a.
  • Consistent mental model: Once you read CSS combinators like binary operators between selectors, the spaces around > stop looking like "descendant selectors" and simply read as breathing room around the > operator.
  • Tooling standard: Formatters like Prettier and linters like Stylelint enforce single spaces around >, +, and ~ by default.

Where a Space Does Cause Real Confusion in CSS

The space-as-descendant-selector trap shows up when there is no >, +, or ~—specifically, when you accidentally add or omit a space between parts of a compound selector:

  • div.active → a <div> that itself has the class active.
  • div .active → any element with the class active nested inside a <div>.
  • ul:first-child vs. ul :first-child → the <ul> itself if it is a first child, versus any first-child element inside the <ul>.

That single space completely changes what gets matched without throwing a syntax error, which is where CSS's choice of whitespace as a combinator genuinely bites developers. Around >, +, and ~, though, spaces are completely safe and standard practice.

Javascript.info sort table exercise; append() automatically removes appended elements from their old position; String localeCompare() is a useful method for sort on string fields; Unicode Root Collation

(In private repo, sort-table-ex-3.html in modifying-document folder is the final solution. Earlier versions with comments are also there.)

This exchange is about my solution to javascript.info exercise: https://javascript.info/modifying-document#sort-the-table. ... My initial solution built HTML tags, which was longish. Javascript.info provided solution was concise. Gem made a point about append automatically removing tr elements from old position which is suitable for this exercise. I used that approach in later versions. Decided to use sort in this solution as I think the javascript.info approach does not bother so much about immutability. Will bear in mind that if I am in React app dev, I should use toSorted() instead.

Me: ... Now about String.prototype.localeCompare() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare .

That seems to be just what is needed for sort on strings.

In your earlier suggested code you have used:


rowA.cells[0].textContent.localeCompare(
    rowB.cells[0].textContent,
    undefined,
    { sensitivity: 'base' }
  )

You wanted to specify options and so had to specify the earlier parameter of locales as undefined. Did I get that right?

Also, Javascript.info tutorial provided solution did not use the options.

Last question: Does your above code do case-insensitive comparison? Probably not.

Gem: You got the first part completely right, and on the last question, it actually does do a case-insensitive comparison.

1. Why undefined Is Passed for locales

Exactly as you guessed: because JavaScript uses positional parameters (not named parameters), you have to pass something for the 2nd argument (locales) in order to reach the 3rd argument (options). Passing undefined tells the engine, "use the browser's default locale, and apply these options."

2. Yes, { sensitivity: 'base' } Is Case-Insensitive

The sensitivity option controls which differences between strings count as unequal. With 'base', only differences in base letters matter—so both case and accents/diacritics are ignored:

sensitivity value Base letters (a vs b) Accents (a vs á) Case (a vs A)
'base' Different Equal Equal (case-insensitive)
'accent' Different Different Equal (case-insensitive)
'case' Different Equal Different (case-sensitive)
'variant' (default) Different Different Different (case-sensitive)

With { sensitivity: 'base' }, 'ann'.localeCompare('Ann', undefined, { sensitivity: 'base' }) returns 0, matching the behavior of your .toUpperCase() comparator. If you want case-insensitivity while still distinguishing accents (a vs á), you would use { sensitivity: 'accent' }.

3. Why javascript.info Omitted options

Unlike raw < and > comparisons—which compare UTF-16 code units and put all uppercase letters ('Z' = 90) before all lowercase letters ('a' = 97)—localeCompare() sorts alphabetically by default, even with no options ('variant').

  • 'ann' < 'Brown' → false ('B' comes before 'a' in UTF-16, which is why you needed .toUpperCase()).
  • 'ann'.localeCompare('Brown') → -1 ('ann' still comes before 'Brown').

Under the default 'variant' setting, case only acts as a tie-breaker when two words have the exact same letters ('ann' vs 'Ann'). For a simple list of names like John, Pete, Ann, plain a.localeCompare(b) already produces the expected alphabetical order without needing any options.

4. Why MDN's localeCompare Page Is Sparse on options

String.prototype.localeCompare() delegates its locales and options handling directly to the Intl.Collator API under the hood. Rather than duplicating the options list, MDN documents all of them on the Intl.Collator() constructor page—including other handy options like { numeric: true }, which sorts "Item 2" before "Item 10" instead of "Item 10" before "Item 2".

(Side note for performance: MDN also notes that if you are sorting a very large array—thousands of rows—creating a single const collator = new Intl.Collator(undefined, { sensitivity: 'base' }); once and passing collator.compare to .sort() is much faster than calling localeCompare() repeatedly inside the loop.)

Me: Noted that sensitivity "base" is case-insensitive - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options does not state it explicitly but says a = A. I missed that on my first reading of the page.

...

Me: U said: (putting ann Lee first in en-US locale, where lowercase sorts before uppercase).

Hmm. I thought uppercase sorts before lowercase as uppercase 'A' has lower 'value' if I may use that term than 'a' (in UNICODE and in ASCII).

Gem: You are completely right about ASCII and Unicode code points: 'A' is 65 and 'a' is 97, so in raw character-code order ('A' < 'a'), uppercase always comes first.

The reason localeCompare() flips that is because it does not sort by code point numbers. Instead, it implements the Unicode Collation Algorithm (UCA)—linguistic sorting rules modeled after human dictionaries rather than binary character values.

Why en-US Puts Lowercase First

  • Dictionary convention: In English dictionaries and indexes, common (lowercase) words are listed before capitalized proper nouns—for example, march before March, polish before Polish, and apple before Apple.
  • UCA default: The Unicode Root Collation (which en-US inherits) adopts this convention, so lowercase sorts before uppercase when two strings differ only in case:
    • 'A' < 'a' → true (UTF-16 code unit order: 65 < 97)
    • 'a'.localeCompare('A', 'en-US') → -1 (linguistic dictionary order: 'a' comes before 'A')

Controlling Case Order Explicitly

If you ever want localeCompare() to remain case-sensitive and put uppercase first (like ASCII), you can pass the caseFirst option:

'A'.localeCompare('a', 'en-US', { caseFirst: 'upper' }); // -1 ('A' before 'a')
'a'.localeCompare('A', 'en-US', { caseFirst: 'lower' }); // -1 ('a' before 'A')

(As a quirk, caseFirst only matters when sensitivity is 'case' or 'variant'. If you pass { sensitivity: 'base' }, 'a' and 'A' are treated as equal (0), so caseFirst has no effect.)

Me: Oh! Dictionary convention is why Unicode Root Collation and localeCompare() flip it. Did I get that right? When did Unicode Root Collation and localeCompare() get adopted in mainstream software dev.?

Gem: Yes, you got that right. Dictionary and linguistic conventions (where common lowercase words like march appear before proper nouns like March) are why the Unicode Collation Algorithm (UCA) and CLDR Root Collation default to lowercase-before-uppercase—though individual locales can override it when their language prefers uppercase first (for example, Danish).

Both Unicode Root Collation and modern localeCompare() became mainstream in distinct waves—first in OSes, databases, and enterprise backends during the 2000s, and then across web browsers in the mid-2010s:

Era Milestone Mainstream Adoption Context
1998–1999 UCA (UTS #10) drafted alongside Unicode 3.0; ICU open-sourced by IBM (1999). Established multi-level linguistic sorting (base letter → accent → case) instead of raw code-point order.
Dec 1999 String.prototype.localeCompare() added in ES3. Only took one argument (a.localeCompare(b)) with no locales or options. Behavior depended on whatever the host OS did, so cross-browser results were inconsistent.
2003–late 2000s Unicode CLDR launched (2003) with its Root Collation table. Adopted by macOS, Windows, Java, .NET, and major databases (MySQL, PostgreSQL, Oracle) via ICU/CLDR. This shift gained momentum after the early-2000s C++ era, when ASCII strcmp() still dominated everyday code.
Dec 2012 ECMA-402 (Intl API / Intl.Collator) standardized. Upgraded localeCompare() to accept locales and options, backed by UCA and CLDR (via ICU inside browser JS engines).
2013–2017 Full browser rollout (Chrome 24 & IE 11 in 2013, Firefox 29 in 2014, Safari 10 in Sept 2016). Once Safari 10 shipped Intl.Collator, localeCompare(str, locales, options) became reliably usable across all major browsers and Node.js without polyfills.

So while localeCompare() technically existed in JavaScript since 1999, the consistent, Unicode-collation-backed version with locales and options only became a mainstream, cross-browser web development standard around 2016–2017.

Me: My last industry project in my first industry stint was on ASP.Net till Aug. 2002 (then break till around end 2024-early 2025). That along with your historical timeline explains why I did not see Unicode Root Collation related stuff in that industry stint. If ASP.Net in 2001-02 was using Unicode Root Collation I think I would have noted it then.

Gem: You are spot on—ASP.NET 1.0 in 2001–2002 was nowhere near Unicode Root Collation.

At that time, Unicode CLDR hadn't even launched yet (it started in 2003), and .NET Framework on Windows relied entirely on Microsoft's proprietary Windows NLS (National Language Support) tables rather than Unicode's UCA/ICU libraries.

In fact, .NET held onto Windows NLS for nearly two decades:

  • .NET Framework 1.0 through 4.8 (2002–2019): Always used Windows NLS under the hood (String.Compare used NLS culture-aware word sorting, while String.CompareOrdinal did raw code-point comparison).
  • .NET 5 (November 2020): That was when Microsoft finally switched .NET on Windows from NLS to ICU (the same Unicode CLDR / Root Collation library browsers use for localeCompare()), so that .NET apps would sort identically across Windows, Linux, and macOS. That switch actually triggered a well-known set of subtle breaking changes in string sorting for teams migrating older .NET Framework codebases.

So your memory lines up cleanly with the history—you wrapped up your ASP.NET stint right before the CLDR/ICU standardization wave took off, and came back right when it had become universal across both browsers and backend runtimes.

Ready to dive into Styles and classes next, or anything else on sorting/collation you want to unpack first?

Me: I am re-reading the localeCompare related exchanges we had, with this knowledge about localeCompare for en-US using Unicode Root Collation order and so handling the 'Z' < 'a' issue. Now it makes lot of sense to me.

The following part of one of your responses gives the key point in the context of this exercise:

So javascript.info's solution is not truly case-insensitive—it differentiates 'ann' from 'Ann'—but it avoids the glaring 'Z' < 'a' bug of raw string comparisons. Passing { sensitivity: 'base' } (or 'accent' if you want to keep a vs. á distinct) is what makes localeCompare() genuinely case-insensitive.

So your code (with { sensitivity: 'base' }) provides the true case-insensitive compare equivalent, whereas javascript.info code trips up on edge case of 'ann' being viewed different from 'Ann', which might result in sort reordering in some cases which is not required/expected for a true case-insensitive sort.

Is my understanding right so far?

Next question: What is standard for case-insensitive (sort) in modern JS apps today? Your code or Javascript.info code? Note that I am not considering my code as it is too lengthy and given the availability of localeCompare() method for String prototype, it makes sense to use it.

Gem: Yes, your understanding is completely right. With { sensitivity: 'base' } (or 'accent'), 'ann' and 'Ann' compare as 0 (equal), so JavaScript's guaranteed-stable .sort() leaves their original relative order untouched. With javascript.info's plain localeCompare(), 'ann' and 'Ann' are treated as unequal, so it will reorder them—which breaks expectations if you specifically want a true case-insensitive sort (or a multi-column sort where equal names should fall back to sorting by Surname or Age).

...

Standard for Case-Insensitive Sorting in Modern JS

  • When true case-insensitivity is required (the { sensitivity: 'base' } approach): Passing { sensitivity: 'base' } is the standard way to get a genuine case-insensitive sort. In real-world UI tables, developers often pair it with numeric: true so strings like "File 2" sort before "File 10":

    a.localeCompare(b, undefined, { sensitivity: 'base', numeric: true })
    
  • When plain a.localeCompare(b) (the javascript.info approach) is used: You will still see plain a.localeCompare(b) very frequently in everyday JS codebases when developers just want quick alphabetical sorting for names or labels and don't mind case acting as a tie-breaker between identical words.

  • For large datasets (production best practice): If you are sorting hundreds or thousands of rows, calling localeCompare() with an options object inside every comparator step can be noticeably slower than reusing a single Intl.Collator instance. Production apps typically hoist the collator outside .sort():

    const collator = new Intl.Collator(undefined, { sensitivity: 'base' });
    trElems.sort((a, b) =>
      collator.compare(a.cells[0].textContent, b.cells[0].textContent)
    );
    

...

For sorting tables and lists, sticking with localeCompare(..., undefined, { sensitivity: 'base' })—and reaching for Intl.Collator when performance matters—gives you both the conciseness of javascript.info and the true case-insensitivity of your earlier .toUpperCase() logic.

(I then incorporated localeCompare() method in later versions of my solution.)

Single quotes ' are more common in modern JS codebases than double quotes "; Both quotes are accepted so long as they are consistently used in codebase

Me: ... Regarding 'base' vs. "base": In general, for strings which do not have quotes within them, what is preferred in JS - ' or ".

Somehow I am used to " - Perhaps in the period of 1984 to 2002 - my first industry stint - " was commonly used and not '. But in JS codebases, I see ' more often than ".

Gem: In JavaScript, single quotes (') and double quotes (") are 100% functionally identical, and the only strict rule is consistency within a codebase. That said, your observation is accurate: single quotes (') are more common across modern JS codebases.

Why your instinct leans toward "

In C, C++, Java, and C#—the dominant languages of 1984–2002—" is required for strings while ' is reserved strictly for single characters (char). JavaScript has no char type, so ' and " are interchangeable for strings, which freed JS developers to adopt ' without any syntax penalty.

Why ' became the dominant JS convention

  • Clean coexistence with HTML and CSS: JavaScript constantly interacts with HTML attributes and CSS selectors, which almost universally use double quotes ("). Using single quotes in JS lets you write '<div class="card">' or document.querySelector('[data-role="nav"]') without ugly backslash escaping (\").
  • Major style guides: The Airbnb JavaScript Style Guide, Google JavaScript Style Guide, and StandardJS all mandate single quotes (').
  • Ergonomics: On a standard QWERTY keyboard, typing ' doesn't require holding Shift.

Where " is still standard in the JS ecosystem

  • Prettier's default: Interestingly, Prettier defaults to double quotes (") out of the box—though many teams override it with "singleQuote": true in their config.
  • JSON: Strict JSON requires double quotes ("); single quotes are a syntax error.
  • JSX attributes: Even in React/Next.js projects that enforce single quotes for JS strings, JSX attributes almost universally use double quotes (<input type="text" />) to match HTML.

For your own code, either ' or " is completely acceptable—nobody in modern JS will fault you for using double quotes as long as a file doesn't mix both for plain strings. If you ever set up Prettier on a project, you can just pick whichever you prefer once and let the formatter enforce it automatically.

(Ravi: MDN states: "Strings declared using single quotes and strings declared using double quotes are the same, and which you use is down to personal preference — although it is good practice to choose one style and use it consistently in your code.")

Optional chaining (?.) cannot be used on the left-hand side of an assignment; Abbreviating code that checks for an HTML element (like <p>) and updates its textContent

Me: JS is quite awesome in abbreviation (though C is king in abbreviation, IMHO). But I am struggling to abbreviate following statements:

    if (document.querySelector('p')) {
      document.querySelector('p').textContent = 'Above table is now sorted on Name.';
    } 

Any suggestions?

Gem: The most idiomatic modern JS approach is to cache the element in a variable so you don't query the DOM twice, then use a compact if:

const pElem = document.querySelector('p');
if (pElem) pElem.textContent = 'Above table is now sorted on Name.';

(Many teams still add braces { ... } around single-line if blocks, though omitting them for a one-liner is common in small scripts.)

The Optional Chaining (?.) Trap—and a Clever One-Liner

The first abbreviation most JS developers try here is optional chaining:

// SyntaxError: Invalid left-hand side in assignment
document.querySelector('p')?.textContent = 'Above table is now sorted on Name.';

JavaScript forbids ?. on the left-hand side of an = assignment. However, ?. does work for method calls. Because Element.prototype.replaceChildren() accepts a plain string (converting it into a text node and replacing any existing children—behaving just like .textContent =), you can write a true one-liner without querying the DOM twice:

document.querySelector('p')?.replaceChildren('Above table is now sorted on Name.');

It is concise, XSS-safe (escapes HTML just like textContent), and does nothing if no <p> is found.

...

Me: replaceChildren() line is good. It is a one-liner. ... But in cases where we have to use an assignment, we have to use the 4 liner you gave, though brace omission makes it a 2-liner. But I thought JS might at least allow let within the if, like it allows let within the for.

Gem: You would think so—especially coming from C++, which has allowed declarations inside if (...) conditions since the 1990s—but JavaScript strictly forbids it:

// SyntaxError: Unexpected identifier 'p'
if (let p = document.querySelector('p')) {
  p.textContent = 'Above table is now sorted on Name.';
}

Why for Allows It and if Doesn't

It comes down to JavaScript's syntax grammar:

  • if (...) only accepts an expression: let, const, and var are declarations, not expressions, so they cannot sit inside if (...) or while (...).
  • for (...) has a special-cased initializer slot: The for loop grammar explicitly carves out its first clause to accept either an expression or a variable declaration (for (let i = 0; ...)).

Why JS Hasn't Added It (Even Though Other Languages Did)

Modern languages like Swift and Rust (if let), Go (if p := ...; p != nil), Python (walrus operator :=), and C++17 (if (auto p = ...; p)) all support scoped declarations inside if. JavaScript's standards committee (TC39) has discussed similar ideas—as well as optional chaining on the left side of = (el?.textContent = ...)—but neither has been standardized for a couple of practical reasons:

  • The = vs. === bug: JavaScript's ecosystem spent years training developers and linters to treat = inside an if (...) condition as a typo for ===. Allowing if (const p = ...) blurs that visual rule.
  • Low urgency in small functions: Because modern JS leans toward short functions, declaring const p = document.querySelector('p'); one line above if (p) rarely clutters a large scope. (If you ever do want to keep p strictly local so it doesn't leak into the rest of a longer function, you can wrap those two lines in a bare block { const p = ...; if (p) ...; }, though that is uncommon in everyday JS.)

So for property assignments in JS, the 2-line const p = ...; if (p) ... pattern is about as concise as the language cleanly gets.

...

Gem: (Ravi: In case of if statement using document.querySelector('p') in condition and also using it for assignment in then block:) Actually, the JS JIT compiler will not optimize away the second document.querySelector('p') call—it will execute two separate DOM lookups.

Why the JIT Compiler Won't Eliminate the Second Call

In C++, a compiler can apply Common Subexpression Elimination (CSE) when it knows a function is pure. A JavaScript JIT (like V8 in Chrome) cannot safely do that for document.querySelector() for two reasons:

  • Cross-boundary C++ call: document.querySelector() crosses from the JavaScript engine into the browser's C++ DOM engine (Blink). To the JS optimizer, it is an opaque external call rather than pure JS math it can prove is side-effect-free.
  • Dynamic language guarantees: Because JS allows objects and methods to be mutated or proxied at runtime, the engine cannot assume two back-to-back calls to a DOM method are guaranteed to return the same result without running the lookup again.

On a tiny page, that extra lookup only takes microseconds, so performance isn't a real-world problem here. The bigger reason JS developers avoid repeating document.querySelector(...) is maintainability: 'p' is short, so duplicating it looks harmless, but once a selector grows to something like '#table + p.status-msg', having it in two places invites copy-paste drift if you ever update one and forget the other.

How Modern JS Resolves the Scope-Clutter Tension

...

  • Just let const live in the function scope (most common): Because modern JS favors short functions (10–25 lines), having const statusElem = document.querySelector('p'); visible for a few extra lines at the end of a small function isn't viewed as scope clutter.
    const statusElem = document.querySelector('p');
    if (statusElem) {
      statusElem.textContent = 'Above table is now sorted on Name.';
    }
    

...

  • A bare block with const (rare, only in long functions): If you ever do want to wall off a temporary variable inside a longer function, you still use const rather than let + assignment-in-if:
    {
      const p = document.querySelector('p');
      if (p) p.textContent = 'Above table is now sorted on Name.';
    }
    

...

Me: (Bare block option) looks good though I have noted what you said about small functions and so letting p be in function scope - I agree with that point. But just in case, I need to limit p's scope, I don't think I can use (Bare block option) due to lack of braces for if. It is not a guard statement. So I think it will have to be something like:

    {
      const p = document.querySelector('p');
      if (p) {
        p.textContent = 'Above table is now sorted on Name.';
      }
    }

Gem: That distinction—allowing brace-free one-liners only for early-return guard clauses (if (!x) return;) while requiring braces for action blocks—is a clean rule, and it lines up well with stricter JS style guides (like Airbnb's, or ESLint's curly rule).

Your braced block is completely valid and well-structured:

  • Single DOM lookup, with const instead of let and no assignment-inside-if.
  • Tight lexical scope so p cannot leak past the closing }.
  • Linter-friendly—even ESLint's no-lone-blocks rule explicitly permits a standalone { ... } block when it contains a const or let declaration, because the block is doing real scoping work.

In a short function, letting const p live in the function scope is still the default, and keeping this braced block in your pocket for the occasional longer function where you want to wall off a temporary variable is a solid pattern.

...

Me: The disadvantage of the replaceChildren() approach is that the API is unusual for this case. So the best solution for typical small functions is:

    const p = document.querySelector('p');
    if (p) {
      p.textContent = 'Above table is now sorted on Name.';
    }

The big thing is avoiding DOM API being called twice even if it is minimal time (as optimizer does not handle it from what you said).

I think I have seen similar code to above in JS codebases. So it is standard stuff.

Gem: You hit the exact nail on the head with replaceChildren()—it is a clever trick, but it fails the principle of least astonishment. Any developer reading p.textContent = ... knows instantly that you are updating text, whereas replaceChildren('...') makes them pause for a second to double-check what it does with a plain string.

That 4-line const + if pattern is genuinely the bread-and-butter standard across professional Vanilla JS codebases. It gives you a single DOM lookup, avoids duplicating the selector, uses the most obvious property for the job, and stays completely linter-friendly without any cleverness tax.

...

24 Nov 2026

VS Code built-in features

In .js files (as per Gem: same for .ts files):

  • For Web/DOM APIs
    • Typing a function like setTimeout shows it in AutoComplete and a box appears with short desc. and signature of setTimeout with MDN page link.
    • Hovering over setTimeout typed in source file shows above box with MDN link.
  • For core JS methods (like Array.prototype.sort), it shows short desc. and signature, but generally without an MDN link.

Built-in F12 (Go to Definition) for quick specs: Put your cursor on .sort and press F12 (or Ctrl+Click) to jump directly into TypeScript's lib.es5.d.ts file. It won't give you an MDN link, but it shows the full overloads, parameter types, and JSDoc comments in one place.

For script elements in .html files, it is similar to .js files mentioned above but without MDN link being shown.

Web search VS Code extension

Gem: A solid, lightweight option for this is Web Search (BenRogersWPG.websearchengine), which supports both a right-click menu and a keyboard shortcut, and lets you add any custom search URL via the Settings UI.

1. Install the Extension

  1. Open the Extensions view in VS Code (Ctrl+Shift+X).
  2. Search for BenRogersWPG.websearchengine (listed as Web Search by Ben Rogers) and click Install. (Alternatively, press Ctrl+P, paste ext install BenRogersWPG.websearchengine, and press Enter.)

2. Add MDN as a Custom Search Engine

You can add it through the Settings UI (no JSON editing required):

  1. Open Settings (Ctrl+,) and search for webSearch.searchEngines.
  2. Click Add Item.
  3. Enter:
  • Key (Item): MDN
  • Value: [https://developer.mozilla.org/en-US/search?q=%s](https://developer.mozilla.org/en-US/search?q=%s)
  1. Click OK.

(If you prefer editing settings.json directly, the entry looks like this:)

"webSearch.searchEngines": {
  "MDN": "https://developer.mozilla.org/en-US/search?q=%s"
}

3. How to Use It

Highlight any method or keyword in your .js, .ts, or .html file (for example, localeCompare or sort), then use either method:

  • Right-click: Select Web Search selected text → pick MDN.
  • Keyboard shortcut: Press `Alt+`` (Alt + backtick) → pick MDN.

Your default browser will open straight to the MDN search results for that highlighted text.

Optional Tip for Generic Method Names

For unique names like localeCompare, searching the highlighted word directly lands right on the page. For short names like sort (which could match Array.prototype.sort or TypedArray.prototype.sort), you can turn on webSearch.addToSelectedText in Settings—it will pop up a quick input box pre-filled with your highlight so you can optionally append a word like array before hitting Enter. If you prefer fewer keystrokes, leave that setting off.

Me: Am trying it. Right-click on highlighted word like sort gives option to do 'Web Search selected text' which then involves pressing Enter on command palette with sort word appearing on it, followed by choosing from list of search engines (including MDN entry I added). Then MDN search fires. I want to reduce the num of steps here. .... Update. I disabled Use Default Search Engines list in the extn settings. That dropped the search engine selection UI (as now I have only MDN).

Gem: Nice catch—disabling webSearch.useDefaultSearchEnginesList is the cleanest way to skip the search-engine picker when you only want MDN.

To eliminate the remaining Command Palette prompt (where sort appears and waits for Enter):

  1. Open Settings (Ctrl+,) and search for webSearch.addToSelectedText.
  2. Uncheck it (set it to false).

With both settings disabled, highlighting a word and clicking Web Search selected text will fire the MDN search directly with zero intermediate prompts.

Two quick ways to shave off the last extra clicks:

  • Use the shortcut instead of right-clicking: Highlight the word and press `Alt+`` (Alt + backtick) to launch the MDN search in one keystroke.
  • Skip VS Code's external-link warning (if it pops up): The first time VS Code asks whether to open developer.mozilla.org, click Configure Trusted Domains and trust the domain so it opens immediately from then on.

Me: webSearch.addToSelectedText set to false dropped that UI step. Great.

Highlight by double-click and Alt+` opens MDN right away with that search. I need to then click on Array.prototype.sort but that's fine.

What's a quick way to highlight word cursor is on using keyboard in VS code?

Gem: Press Ctrl+D once.

  • Ctrl+D (Add Selection to Next Find Match): Pressing it once immediately highlights the entire word your cursor is on, so Ctrl+D followed by *Alt+\``** becomes a fast two-step keyboard flow. *(Just press Ctrl+D` once—pressing it a second time selects the next occurrence of that word in the file.)
  • Shift+Alt+Right Arrow (Expand Selection): A handy alternative when you want slightly more context—the first press highlights the current word, and a second press expands to the surrounding expression (like Array.prototype.sort).

Me: Both worked. (document.querySelector needed the second option). Great! Two qs ...

  1. Single Ctrl+D does not take us into multi-cursor mode - am I right? So no need to Escape out of that mode.
  2. MDN site opens with search list. Then I have to lift my hand off keyboard and use mouse to select the entry from search list. Any quick way to avoid it? I tried tab but it needs too many tabs to get to entries in search list.

Gem: 1. Single Ctrl+D and multi-cursor mode You're right—pressing Ctrl+D once simply selects the word under your cursor and stays in single-cursor mode. You only enter multi-cursor mode if you press Ctrl+D a second time to add the next occurrence, so there is no need to press Esc afterward.


2. Selecting an MDN search result without touching the mouse

Three keyboard-only options, from zero-setup to skipping the list altogether:

  • Ctrl+F → Esc → Enter (fastest built-in browser trick):
  1. Press Ctrl+F and type a few distinguishing characters from the result you want (e.g., array.prototype).
  2. (If the first match isn't the link itself, press Enter to jump to the next match.)
  3. Press Esc—Chrome closes the Find bar while leaving keyboard focus right on that matched link.
  4. Press Enter to open it.
  • Tab → Enter to skip the header: Pressing Tab once on MDN focuses a hidden "Skip to main content" accessibility link at the top of the page. Hitting Enter jumps past the entire top navigation bar, leaving only a few Tab presses to reach the first search result.
  • Skip the search list completely (direct jump to the #1 MDN page): If you want `Alt+`` in VS Code to land straight on the top MDN page without stopping at a search list, you can use DuckDuckGo's direct-redirect (``) URL in your Web Search extension settings:
https://duckduckgo.com/?q=%5C+site:developer.mozilla.org+%s

For unambiguous terms like localeCompare or document.querySelector, it jumps straight to the exact MDN reference page. For broad terms like sort, keeping MDN's own search URL plus the Ctrl+F → Esc → Enter trick gives you more control.

Me: Ctrl+F ... is interesting but needs some typing .... Tab -> enter is great as it jumps to main content. I think that will work out over time. .... Looks like I have a good way to get quickly to MDN ref. page of API/method I need right from VS Code quickly. May turn out to be very useful in future for cases where VS Code built-in support does not show MDN link. Thanks a ton.

Gem: You're very welcome! That Ctrl+D (or Shift+Alt+Right) → Alt+` → Tab→Enterflow is a slick, low-friction setup—and it works across.js, .ts, and .html files without relying on an extension's local index going stale. ...

Comments