liveBook · Manning

Leading underscore convention

As explained in Web Components in Action

The leading underscore convention prefixes an identifier with an underscore to signal intended internal or non-public use without enforcing access restrictions.

A leading underscore signals that a property, variable, or method is intended for internal use. It communicates an API boundary by convention, but it does not prevent outside code from accessing the identifier. section 8.1 section 3.2

Internal rendering method

A component may expose add(item) while reserving _addItemToUI(item) for internal rendering. Calling the internal method directly can add an element without updating the component’s data model, so later redraws may remove it. section 8.1

Use the convention to make an intended boundary visible:

  • Store internal state in names such as _searchTerm and _apiKey. section 3.2
  • Expose searchTerm through a setter while keeping _searchTerm as the underlying value; the setter can trigger doSearch(). section 3.2
  • Treat the underscore as guidance rather than access control; outside code can still call or modify the member. section 8.1
Listing 3.7. Getters and setters for our component’s configurable options
set apiKey(value) {            #1
   this._apiKey = value;
   this.doSearch();
}

set searchTerm(value) {        #2
   this._searchTerm = value;
   this.doSearch();
}

The setter example shows how an underscore-prefixed field can remain internal while a simple public property runs component logic. section 3.2

How Web Components in Action covers it

How deep it goes
Distinguishes convention-based signaling from actual privacy and demonstrates internal state behind setters.
Examples
Uses _addItemToUI, _searchTerm, _apiKey, public setters, and redraw behavior as concrete examples.
What you can do after
Apply it by naming internal component state and methods with underscores while exposing deliberate public properties.
How it connects
Connects encapsulation, private variables, getters and setters, and Web Components.

Also explained in

Compare how 2 books explain leading underscore convention →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.