JavaScript Objects
A JavaScript object is an entity with state and behavior, represented by
properties and methods. Examples include a car, pen, bike, chair, glass,
keyboard, monitor, etc.
JavaScript is an object-oriented language where everything is treated as an
object.
JavaScript is template-based, not class-based. Instead of creating classes to
generate objects, we directly create objects.
Creating Objects in JavaScript
There are three ways to create objects.
1. Using an object literal.
2. By directly creating an instance of Object using the `new` keyword.
3. By using an object constructor with the `new` keyword.
JavaScript Object by object literal
The syntax for creating an object using an object literal is shown below:
Syntax
let objectName = {
propertyName1: value1,
propertyName2: value2,
propertyName3: value3,
};
As you can see, the property and value are separated by a colon (:).
Let’s look at a simple example of creating an object in JavaScript.
Example
<Script>
let car = {
color: 'red',
model: 'Toyota',
year: 2004
};
console.log(car.color);
console.log(car.model);
console.log(car.year);
</Script>
Output :
Red
Toyota
2004
By creating instance of Object
The syntax for creating an object directly is shown below:
Syntax
let objectName = {
property1: value1,
property2: value2,
property3: value3,
...
};
In this case, the `new` keyword is used to create the object.
Let’s look at an example of creating an object directly.
Example
<Script>
let person = {
name: 'Anya',
age: 19,
city: 'Chennai'
};
console.log(person.name);
console.log(person.age);
console.log(person.city);
</Script>
Output:
Anya
19
Chennai
By using an Object constructor
Here, you need to create a function with arguments. Each argument value can be
assigned to the current object using the `this` keyword.
The `this` keyword refers to the current object.
An example of creating an object using an object constructor is shown below.
Example
<Script>
let person = new Object();
person.name = 'kakashi';
person.age = 23;
person.city = 'Chennai';
console.log(person.name);
console.log(person.age);
console.log(person.city);
</Script>
Output:
Kakashi
23
Chennai
Defining method in JavaScript Object
In JavaScript, you can define a method in an object, but before defining the
method, you need to add a property with the same name as the method in the
function.
Example
<Script>
let person = {
name: 'Anya',
age: 19,
city: 'Chennai',
greet: function() {
console.log('Hello, my name is ' + this.name);
}
};
person.greet();
</Script>
Output:
Hello, my name is Anya
JavaScript Object Methods
The different methods of Object are as follows: