Imperative vs Declarative Programming in Javascript
Imperative and declarative programming are two different styles of programming. In imperative programming, we tell the computer what to do step by step, while in declarative programming, we tell the computer what we want to achieve without specifying how to do it. In this blog post, we will explore the differences between imperative and declarative programming in JavaScript with examples.
Imperative Programming
Imperative programming is all about giving the computer a set of instructions to follow. This style of programming is very common in languages like C and Java, where we write code that tells the computer what to do, step by step.
Here’s an example of imperative programming in JavaScript:
1 2 3 4 5 6 7 8 9 10 |
const numbers = [10, 20, 30, 4, 5, 3, 7, 2, 1]; const filteredNumbers = []; for (let i = 0; i < numbers.length; i++) { if(numbers[i] < 5){ filteredNumbers.push(numbers[i]); } } console.log(filteredNumbers); |
In this example, we have an array of numbers, and we want to create a new array with each number less than 5. We use a for loop to iterate over the numbers array and push the numbers that are less than 5 into the filteredNumbers array.
This is a classic example of imperative programming because we’re telling the computer exactly what to do, step by step.
Declarative Programming
Declarative programming is all about describing what we want to achieve without specifying how to do it. This style of programming is very common in functional programming languages like Haskell and Lisp.
Here’s an example of declarative programming in JavaScript:
1 2 3 4 |
const numbers = [10, 20, 30, 4, 5, 3, 7, 2, 1]; const filteredNumbers = numbers.filter(number => number < 5); console.log(filteredNumbers); |
In this example, we have the same array of numbers as before, and we want to create a new array with each number less than 5. However, instead of using a for loop, we use the filter method, which takes a function as an argument and applies it to each element in the array. The filter method returns a new array with the filtered elements.
The key difference between imperative and declarative programming is that imperative programming focuses on how to do something, while declarative programming focuses on what to do. Declarative programming is often more concise and easier to read because we don’t have to worry about the details of how things are being done.
Conclusion
In conclusion, imperative and declarative programming are two different styles of programming. Imperative programming focuses on how to do something, while declarative programming focuses on what to do. In JavaScript, we can use both styles of programming depending on the situation. However, declarative programming is often more concise and easier to read, making it a popular choice among developers.