How / Why Use Objects in JavaScript?
Object oriented Programming (OOP
) in JavaScript is based on a simple object-based paradigm. The name shouldn’t intimidate you as an understanding of objects is cruicial to understanding JavaScript as a whole. Almost everything in JavaScript is an object, functions are objects to and can be passed around as a reference.
We use objects as building blocks for our applications that allow us to adopt valuable industry standard techniques like encapsulation
, inheritance
, polymorphism
. These techniques aren’t new, just like closures
aren’t a new phenomenon - they have been around for a while!
Much like variables are containers for data values, objects are data written as name: value pairs and are extremely useful for making a single unit out of values that are related or belong together. A JavaScript object has properties that are associated with it and the properties of an object succinctly define the characteristics of the object.
Note: Objects don’t have classes like Java, however one way to create and use objects is the constructor pattern. To put it simply an Object is ultimately a function in JavaScript.
Assuming you don’t know much about OOP it’s best to try and understand some of the concepts below while conceptualizing features of an object using the table below:
Object Feature | Concept |
---|---|
Alex is a human | Object(s) |
Alex has black hair, is 6 feet tall and is a female | Object Properties |
Alex can walk, speak and run | Methods |
Alex is an instace of a class homo sapien | Classical class in OOP |
Alex is also based on another object, called creature | Prototype |
By using a simple example, lets create this object with it’s properties
, methods
and a prototype
(which other instances can inherit from):
1 | function Human(firstName, lastName, gender, age) { |
So this works as expected - it might look daunting but if you actually try a practical example and work your way through it, it’s quite easy to understand. Take for example a handful of data elements that pretty much do the same thing but a more functional approach to relatively the same code:
1 | function getFullName(firstName, lastName) { |
Our first example using object s doesn’t inherently provide organizaton, but is extremely useful for orgainzing one’s information (think about hundreds, maybe thousands of instances or functions which result in too much code).
It makes sense to organize your data if can be encapsulated and represented as whole objects rather than just a handful of data elements. Learning how to create and use objects is the first step to OOP, first understand and tackle this and then move on to inheritence.