There are many ways to create the JavaScript object.
1. Object literal syntax
In JavaScript, an object literal is a straightforward way to define objects using key-value pairs. Here’s an example:
const user = { username: "admin", password: "password", roles: ["ROLE_ADMIN", "ROLE_USER"], isActive: true, // Method inside an object displayInfo: function () { console.log(`Username: ${this.username}, Roles: ${this.roles.join(", ")}`); }, };
Object literal property values can be of any data type, including array, function, and nested object.
2. Object constructor
The Object
constructor is a method in JavaScript used to create objects explicitly. While the object literal syntax {}
is simpler and more commonly used, the Object
constructor provides a programmatic way to create objects. Here is an example:
// Create an empty object const user = new Object(); // Add properties and methods to the object user.username = "admin"; user.password = "password"; user.roles = ["ROLE_ADMIN", "ROLE_USER"]; user.isActive = true; user.displayInfo = function () { console.log(`Username: ${this.username}, Roles: ${this.roles.join(", ")}`); };
However, the object literal {}
is preferred and this approach is not recommended.
3. Object’s create method
The Object.create()
method in JavaScript is used to create a new object with a specified prototype object and optionally add properties to the new object.
Object.create(proto, [propertiesObject])
proto
: The object to be used as the prototype of the new object. This can benull
if you don’t want the new object to inherit from any object.propertiesObject
(optional): An object defining properties to be added to the new object. These properties correspond to the descriptors used inObject.defineProperties()
.
Here is an example:
const prototypeObject = { greet: function () { console.log(`Hello, my name is ${this.name}`); }, }; const newObj = Object.create(prototypeObject, { name: { value: "Bob", writable: true, // Allows modification enumerable: true, // Shows up during enumeration configurable: true, // Can be deleted or redefined }, }); // Access properties and methods console.log(newObj.name); // Outputs: Bob newObj.greet(); // Outputs: Hello, my name is Bob
4. Function Constructor
In JavaScript, a Function Constructor is a method to create objects programmatically by defining an object template using a function. When called with the new keyword, the function acts as a constructor and initializes new objects.
function User(username, role) { // Define properties this.username = username; this.role = role; // Define a method this.displayInfo = function () { console.log(`Username: ${this.username}, Role: ${this.role}`); }; } // Create objects using the constructor const user1 = new User("Alice", "Admin"); const user2 = new User("Bob", "User"); // Access properties and methods console.log(user1.username); // Outputs: Alice user2.displayInfo(); // Outputs: Username: Bob, Role: User
5. Function constructor with prototype
This is similar to function constructor but it uses prototype for their properties and methods,
function Person() {} Person.prototype.name = "Sudheer"; var object = new Person();
This is equivalent to creating an instance with Object.create
method with a function prototype and then calling that function with an instance and parameters as arguments.
function func() {} new func(x, y, z);
6. Object’s assign method
The Object.assign()
method in JavaScript is used to copy the values of all enumerable own properties from one or more source objects to a target object. It returns the target object after the properties are copied. Following is the syntax:
Object.assign(target, ...sources)
- target: The object to which properties will be copied.
- sources: One or more source objects whose properties will be copied.
Following is an example:
const target = { a: 1 }; const source = { b: 2, c: 3 }; Object.assign(target, source); console.log(target); // { a: 1, b: 2, c: 3 }
7. ES6 class syntax
In JavaScript, ES6 class syntax provides a more structured and readable way to create objects and implement inheritance compared to traditional function constructors and prototypes. Although it’s primarily syntactic sugar over the prototypal inheritance system, it makes defining and working with object-oriented code easier.
Following is the syntax:
class ClassName { // Constructor method constructor(parameters) { // Initialize properties } // Instance methods methodName() { // Method logic } // Static methods static staticMethodName() { // Static logic } }