Creating new object in javascript
In JavaScript, you can create a new object in several ways:
- Literal notation: You can create an object by using the
{}
syntax and adding properties to it using thekey: value
syntax.const person = { name: 'John', age: 30, occupation: 'Developer' };
- Constructor function: You can create an object by using a constructor function, which is a function that is called with the
new
keyword.function Person(name, age, occupation) { this.name = name; this.age = age; this.occupation = occupation; }
const person = new Person('John', 30, 'Developer');
3. **Object.create()**: You can create a new object by using the `Object.create()` method, which creates a new object that inherits from another object.
const person = Object.create({ name: 'John', age: 30, occupation: 'Developer' });
4. **ES6 classes**: You can create an object by using an ES6 class, which is a syntax sugar for constructor functions.
class Person { constructor(name, age, occupation) { this.name = name; this.age = age; this.occupation = occupation; } }
const person = new Person('John', 30, 'Developer');
5. **Object.assign()**: You can create a new object by using the `Object.assign()` method, which creates a new object and adds properties from another object.
const person = Object.assign({}, { name: 'John', age: 30, occupation: 'Developer' });
6. **JSON.parse()**: You can create an object by using the `JSON.parse()` method, which parses a JSON string and returns an object.
const person = JSON.parse('{"name": "John", "age": 30, "occupation": "Developer"}');
Note that in JavaScript, objects are mutable, meaning that you can add or remove properties from an object after it has been created.