Imperative programming versus declarative programming

Imperative programming is made up of statements that help change the program's state. As mentioned before, it focuses on the how rather than the what. Let's have a look at what this can look like in code to make it more clear:

let sum = 0;

function updateSum(records) {
for( let i = 0; i< records.length; i++ ) {
sum += records[i];
}
}

updateSum([1,2,3,4]);

The preceding code has the following effect: the variable sum is updated when we call updateSum().  We can also see that the function is very explicit about how the summation should happen.

Declarative programming is more focused on what to achieve. It's easy to think of this as being more high-level, because you say what you want to achieve. Let's look at some SQL code. SQL is a declarative programming language:

// content of table 'orderitem'
-------------------
id price productId
-------------------
1 100 1
1 50 11

SELECT
SUM(price) as total
FROM orderitem

// result of the query
150

Here, we are querying a table for a number of records while telling SQL what we want to summarize. We are clearly carrying out the same type of action, which is to summarize something. The difference is that with our declarative example we tell SQL what we want done; we trust SQL to know to summarize. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset