An object is a collection of key-value pairs. To be useful, they should be logically related values.

They can be created with object literal syntax, meaning that the key-value pairs are enclosed in curly braces and usually assigned to a constant or a variable.

At its most basic, an object literal is this:

{}

But more often it is something like this:

const timer = {
  duration: 0,
  started: false,
  startTime: undefined,
  stopTime: undefined,
  start: function() {    
    if (startTime === undefined) 
      startTime = new Date();
    
    started = true;
  },
  stop: function() {
    started = false;
    stopTime = new Date();
    duration = (stopTime - startTime)/1000;
  },
  reset: function() {
    duration = 0;
    started = false;
    startTime = undefined;
    stopTime = undefined;
  } 
}

The value side of the key-value pair can be a literal, an object, an array or a function.

Each key-value pair in an object is known as a member of that object.

Within that, if the value is a function, it is known as a method. This is the Object Oriented Programming way to describe a function that is a member of an object. A method defines some logic and carries out some action. If an object has methods, then it is said to have behaviour.

If a member of an object is not a function, it is known as a property. A property holds values. Those values can be primitive or reference types, so they could be an object or an array.

Members of an object can be accessed using dot notation:

timer.duration
> 0

Or with bracket notation:

timer['duration']
> 0

Or with destructuring:

const { duration } = timer;
console.log(duration);
> 0

And if you have a code editor that has intellisense, such as Atom or Visual Studio Code, you can get a visual prompt as to what members an object has:

Bracket notation is used less than the other two ways of accessing object members, however it is useful when you don’t know until runtime what the keys of an object are. That’s what’s happening in a For…in loop:

for (let key in timer) 
  console.log(key,timer[key])
Object literals and terminology in JavaScript
Tagged on:

Leave a Reply

Your email address will not be published.