JavaScript Prototype Introduction - Programming Paradigms
What is JavaScript Prototype?
December 20, 2024Today, I want to review one of the most important concepts in JS, which is the prototype, but I think it's better to start with the basic, let's review the programming language paradigms first.
What is so-called programming language paradigms?
Think of a tool box, you have a hammer, a screwdriver, a saw, etc. Each tool has its own purpose, and you can solve different problems with different tools, sometime you need to combine them to solve a complex problem, this idea is similar to programming language paradigms.
Programming paradigms are fundamental approaches or styles of programming, it defines the way of thinking and solving problems.
Here are some common programming paradigms and its characteristics:
-
Imperative Programming:
- Change the state of the program by executing statements.
- Focused on how to perform tasks using explicit instructions, such as loops, conditions, etc.
- Example: C, Java.
-
Declarative Programming:
- Describe what to do, not how to do.
- Focused on the result.
- Example: SQL, HTML.
-
Functional Programming:
- functions as the primary building blocks.
- Avoid changing state and mutable data.
- Example: Haskell.
-
Object-Oriented Programming:
- Organize code into objects.
- Encapsulate data and behavior.
- Example: Java, Python.
JavaScript wears multiple hats
JavaScript is a multi-paradigm programming language, it supports OOP concepts, it treats functions as first-class citizens, it can be used in an imperative style or a declarative style.
Let's say we want to filter out the odd numbers from an array, and multiply each number by 2, and then sum them up.
Imperative style
Declarative style
Functional style
Object-Oriented style
Prototype in JavaScript
In OOP, there're two ways to create objects: class-based and prototype-based.
Class-based OOP
It is more traditional, more intuitive, think of a blueprint, you can create multiple instances from the blueprint.
Prototype-based OOP
It is more flexible, it allows you to create objects without a blueprint, simply by cloning an existing object.
Summary
In this article, we've reviewed the programming language paradigms, and how JavaScript supports multiple paradigms, and we've learned the difference between class-based OOP and prototype-based OOP.
- JavaScript is a multi-paradigm programming language.
- JavaScript is a prototype-based OOP language.
- A programming paradigm defines the way of thinking and solving problems.
- There're four common programming paradigms: imperative, declarative, functional, and object-oriented.