Object in javascript is a non-primitive data type, used to hold multiple name-values as properties. Object property is a name:value or key:value pair. Different data types, function can be used with objects.

How to Create an object

Object can be created using following

with {} braces

<script>
const programming = {};
</script>

using Object()

<script>
const programming =  new Object();
</script>

Adding properties to object

<script>
const train = {
  name: "Express",
  arrivaltime: "4:00 PM",
  departuretime: "4:30 PM",
  coaches: 22,
  engine: "electric"
};
</script>
<script>
const train = {};
  train.name: "Express";
  train.arrivaltime: "4:00 PM";
  train.departuretime: "4:30 PM";
  train.coaches: 22;
  train.engine: "electric";
};
</script>

Using the new Keyword

<script>
const train = new Object();

  name: "Express";
  arrivaltime: "4:00 PM";
  departuretime: "4:30 PM";
  coaches: 22;
  engine: "electric";

</script>

What are object properties

Object properties are name value or key value pairs.

<script>
const train = {
  name: "Express",
  arrivaltime: "4:00 PM",
  departuretime: "4:30 PM",
  coaches: 22,
  engine: "electric"
};
</script>

In above example arrivaltime: “4:00 PM”, engine: “electric” and so on are name-value pairs, where arrivaltime and engine is name or key and 4:00 PM and electric is value.

How to Accessing Object Properties

Object properties can be accessed in two ways:

  1. objectName.propertyName
  2. objectName[“propertyName“]
<script>
const train = {
  name: "Express",
  arrivaltime: "4:00 PM",
  departuretime: "4:30 PM",
  coaches: 22,
  engine: "electric"
};
document.write(train.name);
document.write(train["engine"]);
</script>

Adding methods to object

<script>
const train = {
  name: "Express",
  arrivaltime: "4:00 PM",
  departuretime: "4:30 PM",
  coaches: 22,
  engine: "electric",
  start: function(){
      return "Engine started";
  }
};

functions can be added as values to object keys to perform different action or events.