Javascript new object
In JavaScript, there are several ways to create a new object. Here are a few:
- Object Literal: You can create an object using an object literal, which is a collection of key-value pairs enclosed in curly braces
{}
.const person = { name: 'John', age: 30, occupation: 'Developer' };
- Object Constructor: You can create an object using the
Object
constructor function, which takes an optional argument that is an object literal.const person = new Object({ name: 'John', age: 30, occupation: 'Developer' });
- Object.create(): You can create an object using the
Object.create()
method, which takes an existing object as an argument and returns a new object that inherits from the original object.const person = Object.create({ name: 'John', age: 30, occupation: 'Developer' });
- Class: You can create an object using a class, which is a blueprint for creating objects. Classes were introduced in ECMAScript 2015 (ES6).
class Person { constructor(name, age, occupation) { this.name = name; this.age = age; this.occupation = occupation; } }
const person = new Person('John', 30, 'Developer');
5. **JSON.parse()**: You can create an object from a JSON string using the `JSON.parse()` method.
const jsonString = '{"name": "John", "age": 30, "occupation": "Developer"}'; const person = JSON.parse(jsonString);
Note that the `new` keyword is not always necessary when creating an object in JavaScript. However, it is often used to create objects from constructors or classes.