Ways to Define a JavaScript Object:
An object literal is a collection of name:value pairs enclosed in curly braces {}.
{firstName:“John”, lastName:“Doe”, age:50, eyeColor:“blue”} |
Note: Name-value pairs are also referred to as key-value pairs. Object literals are also known as object initializers. |
These examples define a JavaScript object with 4 properties:
Example
// Create an Object const person = {firstName:“John”, lastName:“Doe”, age:50, eyeColor:“blue”}; |
Spaces and line breaks do not affect the functionality. An object initializer can extend across multiple lines.
// Create an Object const person = { firstName: “John”, lastName: “Doe”, age: 50, eyeColor: “blue” }; |
This example initializes an empty JavaScript object and then assigns it 4 properties.
// Create an Object const person = {}; // Add Properties person.firstName = “John”; person.lastName = “Doe”; person.age = 50; person.eyeColor = “blue”; |
This example creates a new JavaScript object using new Object()
, and then assigns it 4 properties.
Example
// Create an Object const person = new Object(); // Add Properties person.firstName = “John”; person.lastName = “Doe”; person.age = 50; person.eyeColor = “blue”; |
Note: The examples above achieve the same result. However, using For better readability, simplicity, and faster execution, prefer using the object literal syntax. |