liveBook · Manning

Declarative programming

As explained in React Quickly, Second Edition

A programming style that specifies the desired result through expressions or descriptions rather than prescribing each execution step.

Declarative programming describes how a result should be, rather than prescribing every step to produce it. In React, this style lets you describe a view while React updates it automatically. The aim is code that is easier to read and understand. section 1.1.1

Compare two ways to count passwords that are at least nine characters long. The imperative version creates an array, loops through passwords, skips short ones, and adds the rest before counting them. section 1.1.1

function countGoodPasswords(passwords) {
  const goodPasswords = [];                     #1
  for (let i = 0; i < passwords.length; i++) {  
    const password = passwords[i];              #1
    if (password.length < 9) {                  #2
      continue;                                 #2
    }
    goodPasswords.push(password);               #1#3
  }
  return goodPasswords.length;
}

The step-by-step version makes each change to the working array explicit. section 1.1.1

function countGoodPasswords(passwords) {
 return passwords.filter(p => p.length >= 9).length;
}

The declarative version expresses the condition with `filter` and counts the resulting array. section 1.1.1

Declarative is not a guarantee of simplicity: taken to an extreme, it can become difficult to read. Prefer the form that makes the intended result clear. section 1.1.1

How React Quickly, Second Edition covers it

How deep it goes
Defines declarative versus imperative style and compares implementations, but does not develop the advanced functional concepts it mentions.
Examples
Compares a manual loop with `filter` when counting passwords of at least nine characters.
What it assumes
Assumes familiarity with basic JavaScript arrays, functions, and loops while defining the two styles directly.
What you can do after
Evaluate/understand it by comparing stepwise code with an expression that states the desired result.
How it connects
Connects declarative programming to imperative programming, React view updates, component-based architecture, and DOM abstractions.

Also explained in

Compare how 14 books explain declarative programming →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.