JavaScript Object

Any value that's not of a primitive type (a string, a number, a boolean, a symbol, null, or undefined) is an object.

Here's how we define an object:


const person = {};

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

You can also use the new Objectsyntax:


const car = new Object();

Another syntax is to use Object.create():


const car = Object.create();

You can also initialize an object using the newkeyword 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 set up 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'

Example


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

const myCar = new Car("Ford", "Fiesta");
console.log(getData(myCar.brand));//'Ford'
console.log(getData(myCar.model));//'Fiesta'

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:

Take this example:


let age = 36;
let myAge = age;
myAge = 37;
age //36

Example


let age = 36;
let myAge = age;
myAge = 37;
console.log(myAge);
console.log(age);

let car = {
  color:"blue"
};
let anotherCar = car;
anotherCar.color = "yellow"
car.color //"yellow"

Example


let car = {
  color:"blue"
};
let anotherCar = car;
anotherCar.color = "yellow"
console.log(car.color); //"yellow"