Algorithm
-
Literal Notation:
- Create an object using
{}
. - Define key-value pairs.
- Create an object using
-
Constructor Function:
- Define a function using
function
. - Use
this
for properties/methods. - Instantiate using
new
.
- Define a function using
-
Object.create():
- Use
Object.create(prototype)
.
- Use
-
Class Syntax (ES6+):
- Define a class using
class
. - Use
constructor
for initialization. - Instantiate using
new
.
- Define a class using
-
Factory Function:
- Create a function returning an object.
Code Examples
#1 Code Example- Using object literal
Code -
Javascript Programming
// program to create JavaScript object using object literal
const person = {
name: 'Akash',
age: 20,
hobbies: ['reading', 'games', 'coding'],
greet: function() {
console.log('Hello everyone.');
},
score: {
maths: 90,
science: 80
}
};
console.log(typeof person); // object
// accessing the object value
console.log(person.name);
console.log(person.hobbies[0]);
person.greet();
console.log(person.score.maths);
Copy The Code &
Try With Live Editor
Output
object
. Akash
reading
Hello everyone.
90
. Akash
reading
Hello everyone.
90
#2 Code Example- Create an Object using Instance of Object Directly
Code -
Javascript Programming
// program to create JavaScript object using instance of an object
const person = new Object ( {
name: 'Akash',
age: 20,
hobbies: ['reading', 'games', 'coding'],
greet: function() {
console.log('Hello everyone.');
},
score: {
maths: 90,
science: 80
}
});
console.log(typeof person); // object
// accessing the object value
console.log(person.name);
console.log(person.hobbies[0]);
person.greet();
console.log(person.score.maths);
Copy The Code &
Try With Live Editor
Output
object
Akash
reading
Hello everyone.
90
Akash
reading
Hello everyone.
90
#3 Code Example- Create an object using Constructor Function
Code -
Javascript Programming
// program to create JavaScript object using instance of an object
function Person() {
this.name = 'Akash',
this.age = 20,
this.hobbies = ['reading', 'games', 'coding'],
this.greet = 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.greet();
console.log(person.score.maths);
Copy The Code &
Try With Live Editor
Output
object
Akash
reading
Hello everyone.
90
Akash
reading
Hello everyone.
90
Demonstration
JavaScript Programing Example to Create Objects in Different Ways-DevsEnv