how to create object dynamically in javascript
How to Create Object Dynamically in JavaScript
Creating objects in JavaScript is a crucial part of programming. Object creation is done in two ways:
- Literal notation
- Constructor notation
Literal Notation
The literal notation is the most common way of creating an object in JavaScript. It involves declaring an object using braces {} and assigning values to its properties:
let person = {
name: 'John',
age: 30,
occupation: 'Programmer'
}
You can also add methods to the object using the same notation:
let person = {
name: 'John',
age: 30,
occupation: 'Programmer',
sayHello: function() {
console.log('Hello from ' + this.name);
}
}
Constructor Notation
The constructor notation is another way of creating an object in JavaScript. It involves creating an object using a constructor function:
function Person(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
let person = new Person('John', 30, 'Programmer');
You can also add methods to the object using the prototype property:
function Person(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
Person.prototype.sayHello = function() {
console.log('Hello from ' + this.name);
}
let person = new Person('John', 30, 'Programmer');
Creating Objects Dynamically
In JavaScript, you can create objects dynamically by assigning properties to an object using square brackets []:
let person = {};
person['name'] = 'John';
person['age'] = 30;
person['occupation'] = 'Programmer';
You can also use the same notation to add methods to the object:
let person = {};
person['name'] = 'John';
person['age'] = 30;
person['occupation'] = 'Programmer';
person['sayHello'] = function() {
console.log('Hello from ' + this.name);
}
Another way of creating objects dynamically is by using the constructor notation and passing the properties as arguments:
function Person(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
let person = new Person('John', 30, 'Programmer');
You can also pass an object containing the properties as an argument:
function Person(person) {
this.name = person.name;
this.age = person.age;
this.occupation = person.occupation;
}
let person = new Person({
name: 'John',
age: 30,
occupation: 'Programmer'
});
In conclusion, creating objects dynamically in JavaScript can be done using either the literal or constructor notation, and by assigning properties or passing them as arguments.