An object literal is simply a plain old JavaScript object that consists of key-value pairs. In the tutorial we will learn how to create objects using object literal with examples.
Object Literal Syntax
The object literal notation is:
- Enclosed inside curly braces
- Uses a color as a separator between a property name and it’s value
- Uses a comma as a separator between each key-value pair
- Optional: Comma at the end of last key/value is syntactically correct but optional
let dog = {
name: "turtle", //Name is "Key" and turtle is value
age: 12,
bark: function () { return console.log("bark"); }
schedule: {
day: "walking",
night: "sleeping"
}
};
Object literals can store complex values, numbers, strings, functions, and nested objects.
Object Literal vs Object()
If you are coming from languages like Java/C#, you might be used to “newing” up objects. JavaScript allows you to do this as well with Object().
let dog = new Object()
dog.name = "turtle"
dog.age = 12