Algorithm


  1. Literal Notation:

    • Create an object using {}.
    • Define key-value pairs.
  2. Constructor Function:

    • Define a function using function.
    • Use this for properties/methods.
    • Instantiate using new.
  3. Object.create():

    • Use Object.create(prototype).
  4. Class Syntax (ES6+):

    • Define a class using class.
    • Use constructor for initialization.
    • Instantiate using new.
  5. 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

x
+
cmd
object
. 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

x
+
cmd
object
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

x
+
cmd
object
Akash
reading
Hello everyone.
90
Advertisements

Demonstration


JavaScript Programing Example to Create Objects in Different Ways-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way