JavaScript Object Literals

By: Dusty Arlia
Published on Tuesday, June 4, 2013, 02:14 PM
Last Updated on Tuesday, July 14, 2015 at 12:18 AM
Total Updates: 5

You can create and initialize JavaScript objects using object literal expressions. An object literal is a comma separated list of name value pairs wrapped in curly braces ({}). They are the most popular way to create objects. Here are two examples of object literals:

var employee = {first_name:"Justin", last_name:"Bieber", id:0001};

Here is the same example, just spanning multiple lines:

var employee = {
    first_name      : "Justin",
    last_name       : "Bieber",
    employee_number :  0001
};

Notice that you do not need a comma after the last property value. You can also create an empty object:

var empty_object = {};

Here is a more complex object that uses the properties of another object:

var Dusty = {first_name:employee.firstName, last_name:employee.lastName, tenure:employee.age-employee.startDate}

If your property name is a JavaScript keyword (e.g. "for") or you have spaces or hyphens in your property name, use quotation marks (e.g. "first name" or 'last name').

Objects created by using object literals use Object.prototype as their prototype.

Besides object literals, you are also able to create new objects using the new operator.

Comments:

Ad: