What is an Object?
Objects are one of JavaScript's data types. An object can be seen as a collection of properties. A property is a name-value pair.
In other words, a JavaScript object is something very similar to a real-life object or entity.
Think a person. A person has different properties like the name or the age. Well... a person can be modeled as a JavaScript object.
There are many ways to create an object in JavaScript.
1. Object() Constructor
- Use the
Object()
constructor to create an empty object. - Set the object's properties.
Example:
// Use the `Object()` constructor to create an empty object
var person = Object();
// Set the object's properties
person.name = "John Doe";
person.age = 42;
2. Create Method
Object.create() can be used to create an object from the prototype of another object.
Example:
var person = Object.create(Person)
3. Object Initializer
- Write the curly brackets {}.
- Put all properties (
name: value
pairs) inside the curly brackets. - Add commas to separate
name: value
pairs.
This is called Object literal (or Object initializer) and can be used to create an object.
Example:
var person = {
name: "John Doe",
age: 42
}
4. Constructor Function
- Create a Constructor Function.
- Use the 'new' keyword to create an object from the constructor function.
Example:
// Create a Constructor Function
function Person() {
this.name = "John Doe";
this.age = 42;
}
// Use the 'new' keyword to create an object from the constructor function
var person = new Person();
5. ES6 Class (only for JavaScript ES6)
- Create a ES6 class containing a constructor method.
- The constructor takes the property values of the object as arguments.
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
var person = Person("John Doe", 42);
6. Singleton Object
A Singleton is an object that can be created only one time. An attempt to create a second object will return a reference to the first object.
Example:
var person = new function(){
this.name = "John Doe";
this.age = 42;
}
Conclusion
In this blog post we have shown 6 different ways to create an object in JavaScript. Every developer should be aware of these ways and choose the most appropriate way from time to time.
That's all for this post. If you liked this post, follow me on dev.to and Twitter (@cscarpitta94) to get notified when I publish new posts. 😊
Top comments (0)