What are JavaScript Objects?

By: Dusty Arlia
Published on Thursday, March 21, 2013, 09:43 PM
Last Updated on Saturday, July 11, 2015 at 7:20 PM
Total Updates: 7

JavaScript objects are components of the JavaScript language that have multiple characteristics known as properties and can perform actions known as methods. JavaScript is not a fully object-oriented language, but it behaves mostly in an object-like manner. Objects are great for things with a lot of properties. They are delimited with curly braces ({}) and inside those curly braces are the object's properties ([property name] : [value]) and methods. The properties are separated by the comma operator (,). Here is an example of an object declaration and initialization:

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
};

These are two examples of object literals. An object literal is a comma separated list of name value pairs wrapped in curly braces. Notice that you do not need a comma after the last property value. Object literals are the most popular way to create objects, but you could also use the new operator like this:

var object_name = new Object;

This way of creating an object is using a function called a constructor. Here are a couple other examples:

new Object()
new Widget(2, 4)

If there are no arguments to get passed to the constructor function, the empty pair of parentheses can be left out:

new Object

JavaScript objects come in many different forms. Each object has its own properties and methods. You can access an object's property value or execute an object's method using dot-syntax. Dot-syntax is the name of the object followed by a dot (period) and then one of its properties or methods. The dot (.) connects the object with its property or method. Here is an example of the document object connecting to its write() method:

document.write('Hello World');

In this example above, the document object uses its write() method to print the string Hello World to the screen.

Here is a different example of an array object named shoppingCartArrayName connecting to its length property:

var i = shoppingCartArrayName.length;

In this example above, the variable i is declared and then assigned the value of the length property of the shoppingCartArrayName array object. This value should be equal to the number of elements in the shoppingCartArrayName array.

Comments:

Ad: