Programming paradigms are a way to classify programming languages based on their features. Some languages are designed to support one paradigm, while other programming languages support multiple paradigms(the trend of times).
The classification in different articles is slightly different, I take the one written in wiki. Common (not all) programming paradigms include:
You arrive at a restaurant, approach the front desk and say…
you asked a question: “I’m by Wal-Mart. How do I get to your house from here?”
Write a function called double which takes in an array of numbers and returns a new array after doubling every item in that array. double([1,2,3]) -> [2,4,6]
function double (arr) {
let results = []
for (let i = 0; i < arr.length; i++){
results.push(arr[i] * 2)
}
return results
}
function double (arr) {
return arr.map((item) => item * 2)
}
Using jQuery (or vanilla JavaScript), add a click event handler to the element which has an id of “btn”. When clicked, toggle (add or remove) the “highlight” class as well as change the text to “Add Highlight” or “Remove Highlight” depending on the current state of the element..
$("#btn").click(function() {
$(this).toggleClass("highlight")
$(this).text() === 'Add Highlight'
? $(this).text('Remove Highlight')
: $(this).text('Add Highlight')
})
<Btn
onToggleHighlight={this.handleToggleHighlight}
highlight={this.state.highlight}>
{this.state.buttonText}
</Btn>
A more complex example[3]:
const numbers = [1, 2, 3, 4, 5, 6];
result = 0;
for (let i = 0; i< numbers.length; i++>) {
if(numbers[i % 2 === 0]) {
result += numbers[i] * 2;
}
}
const numbers = [1, 2, 3, 4, 5, 6];
const result = numbers
.filter(i => i % 2 === 0)
.map(i => i * 2)
.reduce((acc, next) => acc + next);
const numbers = [1, 2, 3, 4, 5, 6];
const isPair = i => i % 2 === 0;
const double = i => i * 2;
const sum = (a, b) => a + b;
const result = numbers.filter(isPair).map(double).reduce(sum);
many declarative approaches have some sort of imperative abstraction layer. Computers don’t understand declarative code, declarative programming still uses imperative programming under the hood.
The declarative response to the restaurant employee is assuming that the employee knows all the imperative steps to get us to the table. Knowing the address assumes you have some sort of GPS that knows the imperative steps of how to get to your house.
the line between declarative and non-declarative at whether you can trace the code as it runs. Regex is 100% declarative, as it’s untraceable while the pattern is being executed.
results
variable in the third example.