It is time to change the subject a bit.


When functions and objects are completely different in other languages, they are very similar in JavaScript.
As I mentioned in one of the previous parts, the object is a collection of name / value pairs.
Each object can contain properties and functions.
In the case, when the function belongs to an object, we call it the method.
Due to the fact that when creating an object we reserve memory, each object has its own address after which we can refer to. It will also have references to its properties too.

There are several ways to create an object in JavaScript.

The first is:

This method is rarely used, but it is good to know that it exists.
In the first line, we create a new object and assign it to a variable named car.
Then, to make the car object to not feel too empty, we create two name / value pairs, which belong only to our object.
The name is in square brackets, and the value after the equal sign.
At the end, we use the already known console.log method to see what will be returned. As you can guess, the console will return the car object and the value we assigned to "maxSpeed", in our case it will be the number 200.

We have access to this value due to the fact that when we created an object, it was saved in the memory along with references to its content.

In the seventh line of our script, we see one way to refer to the properties of an object. Another and at the same time more frequently used is referring by the dot operator (.).

The console.log will return the same in both cases.

As I mentioned before, the property of an object can be yet another object. We can create and assign value to it this way.

Now we can use the table that was posted two parts ago and look for the dot operator.
Since its associativity is left-to-right we would need to type car.engine.model.

Object Literals

Do you remember when I mentioned a few lines above that creating objects through new Object () is not the best solution?
Now I would like to show you another solution.

It looks much better, right? This solution is simply an abbreviation of the previous one.
Thanks to this, we can initiate the object and add properties to it during initialization.

We can also use the method given in line 5. It is not different from the one from the previous example, but for better readability of the code it was written in a few lines.

Next Post

I will talk about a bit more about Object Literals.