Two functions, two moments
init is not a JavaScript keyword. It is a conventional name for the function that answers:
What must happen when this application starts?
Think of opening a classroom. You unlock the room, prepare the material and welcome the students once. That is initialization. During the lesson, you may rewrite the board many times. That is rendering.
function init() {
state.items = resources;
connectEvents();
render();
}
init();
render answers a different question:
What should the interface show for the current state?
function render() {
const visibleItems = getVisibleItems();
renderResources(visibleItems);
renderCount(visibleItems.length, state.items.length);
}
Compare their lifecycles
init() |
render() |
|---|---|
| Normally runs once at startup | Runs at startup and after relevant state changes |
| Obtains initial data | Reads current state |
| Connects event listeners | Updates the DOM |
| Starts the first render | Must remain safe to call repeatedly |
Page and script load
|
v
init() ------------------- once
|
v
render() <----------------+
^ |
| |
state update after an event ----+
Why not attach listeners in render?
If every render calls addEventListener, the same element may receive several identical handlers. One click can then execute the action multiple times. Connect stable listeners during initialization and render changing presentation separately.
Use this simple rule while learning:
Setup that happens once -> init()
Screen update that may repeat -> render()
Predict the call counts
The application initializes once. The user types three characters and each input event calls render(). How often does each function run?
init()runs once.render()runs four times: once during initialization and once per input event.
What to remember
Initialization prepares and connects the application. Rendering synchronizes the interface with current state. init normally runs once; render must support many calls.