DEV Community

Matsu
Matsu

Posted on • Edited on

Programming Paradigms Explained with Code Examples

When you're learning to code or expanding your knowledge, you'll often hear the term "programming paradigms" but what does that actually mean?

A programming paradigm is a way to approach problem-solving using code. It's about how you structure your logic and instructions. Different paradigms shape the way you think and organize your solutions.

Let's explore some of the main ones with simple examples.

1. Imperative Programming

This is one of the most common and intuitive paradigms. You tell the computer how to do something, step by step.

Example (in JavaScript):

let sum = 0;
for (let i = 0; i <= 5; i++) {
  sum += i;
}
console.log(sum); // 15
Enter fullscreen mode Exit fullscreen mode

2. Declarative Programming

You focus on what you want instead of how to do it. SQL and even parts of React are declarative.

Example (SQL):

SELECT * FROM users WHERE age > 18;
Enter fullscreen mode Exit fullscreen mode

Example (React - .jsx file):

function Greeting() {
  return <h1>Hello, world!</h1>;
}
Enter fullscreen mode Exit fullscreen mode

It may not look declarative at first, but the point is: React uses JavaScript under the hood, the way you define UI with JSX is declarative because you're describing what should be rendered based on the current state or props, not how to manually build or update the DOM.

3. Object-Oriented Programming (OOP)

This paradigm organizes code that encapsulate both data and behavior. It's great for modeling real-world entities.

Example (TypeScript):

class Animal {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  speak(): void {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  speak(): void {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog('Rex');
dog.speak(); // Rex barks.
Enter fullscreen mode Exit fullscreen mode

4. Functional Programming

In functional programming, you use pure functions and avoid mutating data. It's about composition, immutability and statelessness.

Example (JavaScript):

const double = (x) => x * 2;
const result = [1, 2, 3].map(double);
console.log(result); // [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Modern languages like JavaScript, Python and TypeScript are multi-paradigm so you can combine functional, object-oriented and imperative styles depending on what fits best.

Here are some languages commonly associated with each paradigm:

Paradigm Languages
Imperative JavaScript, TypeScript, Go, Python, Java, Rust
Declarative SQL, JavaScript (JSX), Elixir
Object-Oriented TypeScript, Python, C#, Java, Kotlin
Functional JavaScript, TypeScript, Python, Kotlin, Elixir

If you're aiming to grow as a developer, understanding paradigms is a powerful step. Knowing the fundamentals helps you understand what you're doing and why you're doing it that way.

Console You Later!

Top comments (0)