What is an object in JavaScript


An object is a unordered mutable collection of primitive and reference data types.

Each item in the collection is a name-value pair and is called property or method (functions are called methods).

Take that object as example:

var car = {brand: "Honda", model:"civic"};

In the example, the properties are brand and model, the values are Honda (for a brand) and Civic (for a model).

Primitive data types and Reference data types

In Javascript an object contains properties or methods. A property, usually is a variable and as we know a variable have (or contains) a value. Well, but what is that have inside? One of the data types supported by Javascript.

There are two kinds of data types: primitive data types and reference data types.

Primitive data type:

Has a fixed size in memory, for example, a number type fills eight bytes of memory, or the boolean, just takes one bit of memory.

There are 6 primitives data types:

  • String.
  • Number.
  • Boolean.
  • Null.
  • Undefined.
  • Symbol ( new in EcmaScript 6).

Store data as a value:

The primitive data type, stores data as a value. That means if we have a variable like that var a = 17; (Number) the primitive value (17) is stored directly in the location of memory that the variable (a) accesses.

Save as value

Reference data type:

Has not fixed size in memory, does mean that can be of any length. For that reason, size doesn’t matter in Arrays or Functions, because they are objects.

There is just 1 reference type:

  • Object.

Store data as a reference:

The reference data type, stores data as a reference. That means if we have a variable like that: var a = {weekDay: "Monday"}; the reference value stored in the variable location is a reference to a location in memory where the object (weekDay: "Monday") is stored.

Save as value

Data as a values VS data as a reference.

To me, this is a very important thing to keep in mind working with JavaScript. Also, is one of the keys to understanding well how works JavaScript.

As in others programming languages, there are three ways that you can manipulate a data value:

  • Copy: assign an actual value to a new variable.
  • Pass: pass a value as an argument to a function method.
  • Compare: compare it with other value to check if they are equal.

Now, let’s take a look how to differ store data as a value vs as a reference.

Copy as a value

// Declare a variable and assign a value.
var a = "Monday";

// Copy the variable's value to a new variable.
var b = a;

// Modify the value of the original variable.
a = "Tuesday";

console.log(b); //Monday, the copy has not changed
console.log(a); //Tuesday, the original change to its new value.

As you can see in the example above, the value in var a is copied to var b but actually, are two separate and independent copies of the value.

Copy by reference

// Initialize a variable refer to an Object.
var a = {weekDay: "Monday"};

// Copy the reference into a new variable
var b = a;

// Modify the value using the original reference
a.weekDay = "Tuesday";

console.log(b.weekDay); // Tuesday
console.log(a.weekDay); // Tuesday

In that case, there is just one value, but two references to the value. Copying by reference just copies the reference to the value, not the value itself. So, changing the value through one of these references will make visible the change in the other references to the value.

Pass as a value

// Declare a variable and assign a value.
var a = 4;

// Define a function that receives a parameter.
function sum(numA){
    numA = numA + 5;
}

console.log(a); // 4 Before call sum();
sum(a); // Call sum() passing the value.
console.log(a); // 4 After call sum();

When you pass as a value, a distinct and independent copy of the value is passed to the function. So, the changes that happen in the copy of that value (within the function) have no effect to the other copies of the value (outside the function).

Pass by reference

// Initialize a variable refer to an Array.
var a = [1,2,3,5,8,13];

// Define a function that receives a parameter.
function changeArray(arrayToChange){
    arrayToChange[0] = 21;
}

console.log(a); // [1,2,3,5,8,13];
changeArray(a); // call changeArray() passing var a.
console.log(a); // [21,2,3,5,8,13];

As we saw previously, any change that occurs through the reference of a value, it will reflect in the other references to that value.

So, the changes that happen within the function through the reference, it takes effect outside the function.

Compare as value

// Initialize two variables and assign the same values.
var a = 1;
var b = 1;

// Compare if values are equal.
if(a == b){
    console.log('a and b are equals');
}else{
    console.log('a and b are not equals')
}

// a and b are equals.

Comparing values look easy, isn’t? without any information about JavaScript, just with the idea to compare, I can imagine how will work the comparison. It takes the value of A and compares with the value of B, if they are equal return true, if not, false. Easy peasy.

Compare by reference

// Initialize two variables and refer to an Array.
var a = [1,2];
var b = [1,2];

// Compare if values are equal.
if(a == b){
    console.log('a and b are equals');
}else{
    console.log('a and b are not equals');
}

// a and b are not equals.

The obvious things, turn a little less obvious when comparing by reference.

Why? because comparing by reference, it doesn’t compare the value in itself, it compares if they are referencing to the same value.

So, A and B, look equals, they are two arrays with the same information, but the references are different, are referencing different values. And this is the reason why A and B are not equals.

Well, for now, this is a basic explanation of what is an object in JavaScript.

Creating objects

Because this is a big (and important) topic, I will explain briefly and in the near future, I will write and entire post about creating objects in javascript.

There are two common ways to create an object, we will take object literal way for the example.

You just have to assign { } to a var.

// Create an empty object
var car = {};

// Assign properties.
car.brand = "Honda";
car.year = 2004;
car.model = "Civic type r";

// Assign function to a property.
car.whoAmI = function(){
     console.log("I am "+car.brand+" "+car.model+" from "+car.year);
}

Object properties

Again, this is a big topic too. So I will explain briefly and in the near future, I will write a post explaining in deep object properties.

Objects have properties and methods (also called functions). In the example above (creating objects), we check how objects are created, but also how properties of the object are assigned.

The property is commonly associated with a name-value pair but is not only that, the value is one of the property’s attributes but there are 3 more (all 3, by default, are set to true):

  • Configurable: can the value be deleted or changed?
  • Enumerable: can be accessed? (notice that I am not saying read, is different).
  • Writable: is the value writable?

Accessing to the properties

The property can be own or inherited, but I will cover that in the future object properties post. Let’s take just the owned properties of the object for the example.

For access to the enumerable property of an object you can do it with a dot notation if you know the name of the property:

// Create the object and assign properties
var car = {brand: "Honda", year: 2004, model: "Civic type R"};

console.log(car.brand) // Honda
console.log(car.model) // Civic type R

Or using a for/in loop or a general loop like this:

// Create the object and assign properties
var car = {brand: "Honda", year: 2004, model: "Civic type R"};

// Loop through the enumerable object properties
for(var property in car){
  console.log(property);
}

Adding properties

You can add properties to an object in the initialization of it (as in the example of accessing to the properties) or after his creation.

// Create an empty object
var car = {} ;

// Add some properties
car.brand = "Honda";
car.year = 2004;
car.model = "Civic type R";

console.log(car); // {brand: "Honda", year: 2004, model: "Civic type R"}

Deleting properties

You can delete properties of an object with the delete operator.

// Create the object and assign properties
var car = {brand: "Honda", year: 2004, model: "Civic type R"};

// Delete some properties
delete car.model;
delete car.year;

console.log(car); // {brand: "Honda"}

So, ¿that is all?

Well, as I mentioned more than once, some topics of the post (creating objects, objects properties, etc) are pretty big and interesting to explain in deep here. So I will try to write some posts about it in the near future.

References:
JavaScriptisSexy - JavaScript Objects in Detail
Primitive types and Reference types
By value vs By reference
MDN - JavaScript data types and structures
stack overflow - Primitive value vs Reference value
delete operator