Skip to content

Commit 42503b6

Browse files
committed
imperative vs declarative examples
1 parent c7f2d0d commit 42503b6

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

FunctionalProgramming.md

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,4 +82,22 @@ A useful analogy to think of is that computers are better at being imperative an
8282

8383
![Imperative Vs. Declarative](./Assets/ImperativeDeclarative.png)
8484

85-
Machine code is very imperative. When we declare a variable the computer receives a lot of specific instructions on where to put it in which memory space, when to modify it and so on. Its very descriptive of how to do things. In contrast, as we go higher up the chain to a higher level language, it becomes more declarative. Instead of giving specific instructions of where to store it in memory etc, we just declare the variable with some sort of data and tell it what we need to get done but not how to do it. The computer takes care of that for us.
85+
Machine code is imperative. When we declare a variable the computer receives specific instructions related to where it should be stored in memory space, when to modify it and so on. Its very descriptive about how to do things. In contrast, as we go higher up the chain to higher level languages it becomes more declarative. Instead of giving specific instructions, we just declare the variable with some sort of data and tell it what we need to achieve but not how to do it. The computer takes care of that for us.
86+
87+
<i>JQuery is an example of a fairy imperative language, and the React framework operates in a fairly declarative fashion.</i>
88+
89+
<i>Example:</i>
90+
91+
`for` loops can be considered an imperative style of writing code
92+
93+
```javascript
94+
for (let i = 0; i < 1000; i++) {
95+
console.log(i) // -> 1,2,3,4...1000
96+
}
97+
```
98+
99+
One way of making a `for` loop more declarative is to use `forEach()` instead
100+
101+
```javascript
102+
[1,2,3].forEach(item => console.log(item)) // -> 1,2,3
103+
```

0 commit comments

Comments
 (0)