ยท hands on
How to write declarative TypeScript Code?
Declarative programming in TypeScript focuses on defining the desired outcome rather than the specific steps to achieve it. It simplifies code by abstracting control flow and state management, relying on functions like filter to handle details.
Declarative programming lets you define what you want without detailing how to get there. It's the essence of functional programming languages, focusing on results rather than steps.
Let's break down the difference between imperative and declarative programming in TypeScript with a straightforward example: filtering out even numbers from an array.
Contents
Imperative Programming
Imperative programming details how to perform tasks step by step, explicitly describing the control flow and state changes. You explicitly define each step that the code should take to achieve a specific goal. This approach emphasizes how to perform tasks by focusing on the flow of control and the state changes in the system.
Example
In the imperative example, we define how to store our results by iterating over all numbers and checking if each number passes the modulo operation. We then manually add the passing numbers to our results array.
Declarative Programming
Declarative programming focuses on what the result should be rather than how to achieve it. This approach abstracts away the control flow and state management, letting the underlying system or library handle those details. Its mostly reliant on APIs.
Example
In the declarative example, we only specify our goal to keep numbers that satisfy the condition n % 2 === 0
, and the function takes care of the rest.
Imperative vs. Declarative
Comparison Table
Aspect | Imperative Programming | Declarative Programming |
---|---|---|
Control Flow | You manually loop through each element using a for loop. | You don't explicitly manage the loop; the filter function handles it internally. |
State Management | You explicitly manage the state by pushing even numbers into the evenNumbers array. | You don't manage the state explicitly; the filter function returns a new array. |
Focus | The code focuses on the exact steps required to achieve the result. | The code focuses on the final result, specifying the condition for filtering, without concern for how. |