Objects in JS - Part 1

What is an Object?

 

  • Object is a collection of properties. Simply, object are collections of key and value pair.

  • Object can be compared to any real world entity like car, train or cup.

  • Real world objects will have its own property.

For example, a car can have properties like color, engine capacity, transmission type, fuel type etc.,

 

How to create an Object??

There are three ways to create an object in JS,

 

1. Create using object initializers

2. Using new Object

3. Use Object.Create()

Create using object initializers

const car = {
    color: 'red',
    transmissionType: 'auto',
    company: 'TATA',
};

Easier way to create an object is using initializers like this,

An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

Using new Object

Object can be created using new operator on Object constructor.

const car = new Object({
    company: 'TATA',
    model: 'TIGOR',
});

car.color = 'RED';

Using object create method

Object can be created using Object.create method

const car = Object.create(Object.prototype, {
    model: {
        value: 'TIGOR',
        writable: true,
    },
    company: {
        value: 'TATA',
        writable: true,
    },
});

console.log(car);

That's it!! Now, you know

how to create objects in JS

Objects in js

By hentry martin

Objects in js

  • 201