You will discover various methods for creating JavaScript objects in this example.
You should be familiar with the following JavaScript programming concepts to comprehend this example:
- Objects in JavaScript
- Constructor function in JavaScript
An object can be made in one of three ways:
- The use of object literal
- By explicitly constructing an Object instance
- Making use of the constructor function
Example 1: The use of object literal
// a programmer that uses object literals to construct JavaScript objects
const person = {
name: 'Shailesh',
age: 20,
hobbies: ['reading', 'cricket', 'coder'],
common: function() {
console.log('Hello everyone.');
},
score: {
maths: 90,
marathi: 80
}
};
console.log(typeof person);
console.log(person.name);
console.log(person.hobbies[0]);
person.common();
console.log(person.score.maths);
Output
object
Shailesh
reading
Hello everyone.
90
We have generated an object called person in this code.
An object literal can be used to build an object. To generate an item directly, an object literal employs the symbol.
A key:value pair creates an object.
Functions, arrays, and even objects can all be defined inside of another object. Using dot notation, you can get at the object's value.
The following syntax is used to create an object using an object instance:
const objectName = new Object();
Example 2: By explicitly constructing an object instance
// a programmer that uses object literals to construct JavaScript objects
const person = new Object ( {
name: 'Shailesh',
age: 20,
hobbies: ['reading', 'cricket', 'coding'],
common: function() {
console.log('Hello everyone.');
},
score: {
maths: 90,
science: 80
}
});
console.log(typeof person);
console.log(person.name);
console.log(person.hobbies[0]);
person.common();
console.log(person.score.maths);
Here, an object is created by using the new keyword together with the Object() instance.
Example 3: Create an object using Constructor Function
// program to create JavaScript object using instance of an object
function Person() {
this.name = 'Shailesh',
this.age = 20,
this.hobbies = ['reading', 'cricket', 'coding'],
this.common= function() {
console.log('Hello everyone.');
},
this.score = {
maths: 90,
science: 80
}
}
const person = new Person();
console.log(typeof person); // object
// accessing the object value
console.log(person.name);
console.log(person.hobbies[0]);
person.common();
console.log(person.score.maths);
The new keyword is used in the example above to create an object using the Person() Constructor function.
An object is made by calling new Person().