(click anywhere to close)

[JavaScript] Objects

category: Website | course: JavaScript | difficulty:

Finally, we’ve arrived at the big guns. The last of the great data types, which represents everything that JavaScript is.

Objects are unordered lists of values and functions

At first look, this seems like an upgrade to arrays. Why is this its own data type and an array isn’t? Because it’s actually the other way around – an array is just a simplified version of an object.

Arrays only represent lists of numbers with corresponding values. Objects can also link strings with values, and can contain those functions we’ve been calling methods.

This means that objects in JavaScript are exactly like objects in the real world; they have a certain set of properties and functions. Objects of the same kind have the same properties, but with different values, and the same methods, but executed at different times.

For example, a computer, as an object, has properties like brand, screen size, operating system, memory. Two computers can have different values for screen size, but a computer will always have a screen. A computer also has functions like starting up and shutting down, but computers don’t all have to shut down at the same time, and the way they shut down depends on its operating system property.

Knowing this, we can define objects we can copy easily and use in numerous ways.

Declaring Objects

The literal syntax for declaring an object is

{ property: value, property: value, … }

var user = {
	updateCredits: function() {
		return "You can't.";

The properties follow the same naming rules as variables. Values can be anything.

Accessing Properties & Methods

There are two ways to access properties or methods:

  • Dot notation: object.property
  • Array notation: object[“property”]

They both do exactly the same, but the second is more secure. With the first one, you might run into problems when your property is a reserved word (like, for example, length).

var x = user["username"]; //x is "Johnny"
x = user.username; //x stays the asme

var y = user.updateCredits(); //y is "You can't."
y = user["updateCredits"](); //y stays the same

Copying Objects

Just like Arrays, when you assign an object to a new variable, it simply creates a reference. Arrays had the solution of using slice, but objects don’t have such a method. Instead, if you want to copy an object, you’ll have to create a new object and transfer all properties. This is quite complex, and you’ll learn about it later.

Do you like my tutorials?
To keep this site running, donate some motivational food!
Chocolate Milk