Use Object.create() method to create a new object in JavaScript. It will use an existing object as the prototype of the newly created object.
Use Object Literal to create a new object.
Objects are variables but objects can contain many values. Objects are written as name: value pairs (name and value separated by a colon).
let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
JavaScript Creates a new object
A simple example code declares objects with the const
keyword. The easiest way to create a JavaScript Object using an Object Literal.
Spaces and line breaks are not important.
<!DOCTYPE html>
<html>
<body>
<script>
const emp = {firstName:"John", lastName:"Doe", age:25, city:"NY"};
console.log(emp)
</script>
</body>
</html>
Output:
The below example creates an empty JavaScript object, and then adds 4 properties:
<script>
const agent = {};
agent.firstName = "Jems";
agent.lastName = "Bon";
agent.age = 100;
agent.eyeColor = "blue";
console.log(agent)
</script>
Output: Object { firstName: “Jems”, lastName: “Bon”, age: 100, eyeColor: “blue” }
Create a new JavaScript object using new Object()
.
const agent= new Object();
agent.firstName = "Jems";
....
Using an existing object as the prototype
<script>
const emp = {firstName:"John", id:"A1", age:25, city:"NY"};
const me = Object.create(emp);
me.firstName = "Steve";
me.id = "A2"
console.log(me)
</script>
Output: Object { firstName: “Steve”, id: “A2” }
Do comment if you have any doubts or suggestions on this Js object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version