As introduced in the types section, any value that’s not of a primitive type (a string, a number, a boolean, a symbol, null or undefined) is an object. Even arrays or functions are, under the hoods, objects.

Here’s how we define an object:

const car = {

}

This is the object literal syntax, which is one of the nicest things in JavaScript.

You can also use the new Object syntax:

const car = new Object()

Another syntax is to use Object.create():

const car = Object.create()

You can also initialize an object using the new keyword before a function with a capital letter. This function serves as a constructor for that object. In there, we can initialize the arguments we receive as parameters, to setup the initial state of the object:

function Car(brand, model) {
  this.brand = brand
  this.model = model
}

We initialize a new object using

const myCar = new Car('Ford', 'Fiesta')
myCar.brand //'Ford'
myCar.model //'Fiesta'

Objects have properties. Every property has a name and a value.

You might think an object is basically a map, or dictionary, data structure, and you would be correct.

The value of a property can be of any type, which means that it can even be an object, as objects can nest other objects.

When a property value is a function, we call it method.

Objects can inherit their properties from other objects, and we’ll see this in details when we’ll talk about inheritance.

Objects are always passed by reference.

If you assign a variable the same value of another, if it’s a primitive type like a number or a string, they are passed by value:

let age = 36
let myAge = age
myAge = 37
age //36
const car = {
  color: 'blue'
}
const anotherCar = car
anotherCar.color = 'yellow'
car.color //'yellow'

This is a key concept to understand, so play around with this.


Go to the next lesson