The Ultimate Guide to Objects in JavaScript
A Complete Beginners Guide to Objects in JavaScript
The definition of an object is anything that has a property and values.
Just like physical objects, Javascript objects have properties of any data type. Such properties also have values. For example, you could have a Person object with name, height, and weight as properties, with each property being assigned to a value like this.
property:value
Create an Object in JavaScript
There are several ways to create objects in javaScript namely:
using object literals
using the function Constructor
using Object.create()
Using object literals
Object literals is a way of creating objects by specifying the object properties or methods when creating the object. To define an object using object literal syntax, we enclose key-value pairs in curly braces like this:
const newObject = {
property1: value1,
property2: value2
}
Objects can contain multiple data types, such as numbers, stings, Arrays, or objects. For example, letβs define a person with name and age properties
const person = {
name: "Joe doe",
age: 30
}
To get the value of a property, you can use the dot notation or bracket notation like this:
console.log(person.name) // dot notation
console.log(person.age) // dot notation
console.log(person['name']) // bracket notation
console.log(person['age']) // bracket notation
Both the dot notation and the bracket notation will give the same result.
Joe doe
30
Joe doe
30
An object is mutable, meaning we can add, update, or remove properties. For example, suppose we need to update the age of the person object; we can use the dot notation or the bracket notation like this:
person.age = 31
console.log(person) //{ name: 'Joe doe', age: 31 }
// update the age again
person.age = 32
console.log(person) // {name: 'Joe doe', age: 32}
We can also add new properties to the person object using either the dot notation or the bracket notation, as shown below
person.height = 186 //dot notation
person['weight']= 143 // bracket notation
Both dot notation and bracket notation work the same. Now, if we check the object, it has more properties.
console.log(person)
// { name: 'John doe', age: 31, height: 186, weight: 143 }
However, bracket notation is suitable if the property starts with a number, contains spaces, or includes special characters unsuitable with the dot notation.
person['job title'] = "Software Developer";
console.log(person)
To access the property, you also need to use bracket notation.
person['job title'] = "Software Developer";
console.log(person['job title']); // Output: "Software Developer"
Lets add an hobbies array to the person object.
person.hobbies = ['swimming', 'cooking']
Now the person object looks like this:
{
name: 'John doe',
age: 31,
height: 186,
weight: 143,
'job title': 'Software Developer',
hobbies: [ 'swimming', 'cooking' ]
}
You can also delete properties using the delete operator, for example suppose you need to delete some properties of the person object; the syntax would look like this:
delete person['job title'] // bracket notation
delete person.hobbies //dot notation
Object methods and this Keyword
We mentioned earlier that an object can take in a function as a property. A property function inside an object is known as a method. Letβs define a details property to our person
object and assign it to a function.
person.details = function(){
console.log(`My name is ${this.name} and am a ${this['job title']}`)
}
Here we are adding a function called details which logs the details of the person to the console.
The this
keyword in JavaScript is used within the context of functions, especially when they are methods of objects like our person
Object. In this context, this refers to the person object; therefore, this.name
is equivalent to person.name.
Since details is a method, it should be called as follows with parentheses.
console.log(person.details())
// My name is Joe doe and am a Software Developer
Using the Object.create()
method
Using the Object.create()
method is another way of creating an object in JavaScript. This method allows you to set up prototype-based inheritance, Unlike Object literals, where you would have to duplicate properties for each Object.
So, for example, any newly created objects will inherit the properties and methods defined in the personPrototype
Object.
let personPrototype = {
greeting: function() {
console.log('Hello!');
}
};
let person1 = Object.create(personPrototype);
person1.name = 'joe';
person1.age = 30;
console.log(person1) //output //{ name: 'joe', age: 30 }
If we use developer tools, we can see the inherited Prototype.
Using the function Constructor
Using the function constructor is another way of creating a new object. A javascript function constructor for the person
object will look like this:
function Person(name, height,skills,hobbies){
this.name =name;
this.height = height;
this.skills = skills;
this.hobbies = hobbies;
}
Once you define the object using a constructor, you can create a new instance of an object using the new keyword and pass the values as shown below.
person1 = new Person('joe',30, ['python','js'], ['reading']);
console.log(person1)
Itβs also important to note that when passing arguments, the order of the arguments must match the order of the parameters. In our case, the order of the parameters is name
, height
, skills
, and hobbies
.When you log the person1
instance to the console, you will get this output.
Person {
name: 'joe',
height: 30,
skills: [ 'python', 'js' ],
hobbies: [ 'reading' ]
}
To add new properties to the Person
function constructor, you must explicitly define it in the constructor or use functionβs prototype. Letβs add a new property called personality
. Our constructor now looks like this.
adding a property to the function constructor
function Person(name, height,skills,hobbies,personality){
this.name =name;
this.height = height;
this.skills = skills;
this.hobbies = hobbies;
this.personality =personality;
}
using the constructors function prototype
function Person(name, height,skills){
this.name =name;
this.height = height;
this.skills = skills;
}
Person.prototype.personality = 'ENJT';
let person1 = new Person("Alice", 160, ["JavaScript", "HTML"]);
The ouput will be:
Alice
160
[ 'JavaScript', 'HTML' ]
ENJT
You can add a new property or update the value of a property directly to the object instance. Lets update the personality property of person1
object instance.
person1.personality = 'ISFJ'
console.log(person1)
So now the object instance looks like this:
Person {
name: 'Alice',
height: 160,
skills: [ 'JavaScript', 'HTML' ],
personality: 'ISFJ'
}
Manipulating Objects
JavaScript provides inbuilt methods for manipulating objects which include:
Object.keys()
Object.values()
Object.entries()
Object.keys()
Object.keys()
is used to get all the keys of the object passed as an argument and outputs an array of keys.
For example, consider our person object.
const person = {
name: 'John doe',
height: 30,
skills: ['python', 'JavaScript']
};
const keys = Object.keys(person);
console.log(keys);
The output will be:
[ 'name', 'height', 'skills' ]
Object.values()
Object.values is similar to Object.keys() but instead returns an array of the object values.
const person = {
name: 'John doe',
height: 30,
skills: ['python', 'JavaScript']
};
const values = Object.values(person);
console.log(values);
The output will be:
[ 'John doe', 30, [ 'python', 'JavaScript' ] ]
Object.entries()
Object.entries()
when applied on an object will return an arraay containing the keys and values of the object.
const person = {
name: 'John doe',
height: 30,
skills: ['python', 'JavaScript']
};
const entries = Object.entries(person);
console.log(entries);
The output will be:
[
[ 'name', 'John doe' ],
[ 'height', 30 ],
[ 'skills', [ 'python', 'JavaScript' ] ]
]
Object Destructuring
Destructuring is used in Javascript to make code more flexible and concise. It involves taking properties from objects and setting them as local variables. For example, consider an employee object with 3 properies as shown below.
let employeee = {
firstName: 'Joe',
lastName: 'Doe',
age: 30
};
After destructuring we will have this:
let { firstName, lastName, age } = employeee;
If we want to get the values of the properties, we only have to call them without referring to the object itself.
console.log(firstName);
console.log(lastName);
console.log(age);
Conclusion
This Guide has covered different ways of creating objects, adding methods to objects and inbuilt ways to manipulate objects. These concepts will help you when working with data in your applications.