Object Literal in JavaScript

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:

  1. Enclosed inside curly braces
  2. Uses a color as a separator between a property name and it’s value
  3. Uses a comma as a separator between each key-value pair
  4. 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

Leave a Reply

Your email address will not be published. Required fields are marked *