Demystifying Objects - Part One
Objects like in any other programming language are collection of properties where properties are defined by a name followed by a value. This data-type is often used to define something which has many properties associated with it. Properties in Objects are variables which will have corresponding value stored in it.
1. Object Initialiser
The most common way of creating an object is by using object initialiser. Object initialiser is nothing but a comma-delimited list of zero or more pairs of property names and associated values, enclosed in curly braces
In the above example,
blog is the name of the object,
language are the properties and
English are the values associated with the properties respectively. Objects created using
object initialisers are always instances of
2. Constructor Function
This is a method where we define the type of the object using a constructor function and create an instance of Object using the
The constructor function defines the type of the Object by providing name, properties and a method for the type.
In this example
myBlog is an object which is of the type
English would be the values of the properties
language respectively. If you notice in the constructor function, we have used the
this keyword. Here,
this is mainly used to assign the values to the properties based on the values passed to the function.
3. Object.create() method
This is a method which helps to create a new object using existing object as the
As mentioned above,
Properties can be accessed either using
In the above example,
blog.type would be valid way of defining a property in
blog object as the property name
toString() method. If you look at the next line
How do we fix the above example ?
In these cases we can make use of
bracket notations where we can create/access properties which are not adhering to identifier rules or are not strings. So the final code will look as below
bracket notations are generally used when we want dynamic properties or in case where we need to access/create properties which are numbers, names stored in variables etc.
In one of the above sections we mentioned that Objects values are passed by reference. What does this actually mean ?
In the above example we have a function
changeValue whose purpose is to change the property
oldObject is our default object that we created which has a property
first containing a value
On calling the function
changeValue by passing our
newObject variable to already existing property
first: false. On executing
newObject.first = true, will change the property
first where in
newObject.first will show
true as both are pointing to the same property.
- How to access Object Properties
- What is pass-by-reference
Until we meet again, The Mallu Dev signing off 👋 Cheers 🥂