Objects

Everything in JS is an object

Except the primitives

Anything that is not a primitive value is an Object. That includes arrays, functions, and objects themselves.

An object is a

collection of properties

A property is a
named container for a value
w/ some additional attributes

The name of a property  is called a key ;
thus, an object  can be considered as
a collection of key-value pairs .

There are similar concepts in other programming languages,
e.g., Map, Dictionary, Associative Array, Symbol Table, Hash Table , ...

Properties

  • all objects in JavaScript are maps (dictionaries) from strings to values.

  • A (key, value) entry in an object is called a property .  The key of a property is always a text string (in ES5).

  • 3 Kinds of Properties

  • Properties (or named data properties)

  • Accessors (or named accessor properties)

  • Internal properties

    • Exist only in the ECMAScript language specification.

 

Creation of Objects

Literal Notation

const obj = { }; 
// Creating an object using literal notation
const obj = {
  firstName: 'Alex',
  'lastName': 'Martin', // Using string quotes
  dateOfBirth: '18th October',
  friends: [ 'Bob', 'Christine' ]
};
  • An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string.
  • The values can be any JS type.
  • The nesting of objects can be arbitrary and cyclic too!

Object Constructor

Object.create

const obj = new Object();
obj.name = 'arfat'
  • This effect of this code and the literal notation is the same.
  • However, it is advised not to use this pattern.
const newObj = Object.create(Object.prototype);

newObj.name = 'arfat'
  • This lets you specify the "prototype" of an object at the time of definition.

Adding / Updating Properties

Dot Notation

$ jane.name = 'JANE'
$ jane['desc.func'] = function () {
  return 'NEW FUNCTION'
}

Bracket Notation

  • An object can only contain a single key with one value.
  • Using the dot-notation, you can’t use property names that are numbers, or string that contain spaces, or special character, or dynamic properties.
  • Use bracket Notation to overcome these.

Accessing Properties

Dot Notation

var jane = {
  name: 'Jane',

 'desc.func': function () {
      return 'Person named ' + this.name;
  },
};
$ jane.name

// 'jane'
$ jane['desc.func']

// [Function]

Bracket Notation

Note: Accessing non-existing properties give `undefined`

Deleting Properties

Deletion is performed using thedelete operator. Again, we can use both the notations.

delete obj.firstName;      // => true
delete obj['firstName'];   // => true

Note: The return value of delete operator is true if the property was successfully deleted. Else, it will be false.

Function as key values

  • In an object, when we have a function as a value to a key, then the function is called a method. This is one of the most important features of objects.
  • The methods have access to the key-value pairs of the object.
  • They can specify behavior in an object.
const obj1 = {
  fName: 'ALEX',
  lName: 'MARTIN',
  printFullName() {
    return this.fName + ' ' + this.lName;
  },
};

obj1.printFullName();
//=> 'ALEX MARTIN'

Delegation (of Properties)

  • Reading a property in JS is not a simple operation.
  • In JS, objects are not just containers of key-value pairs.
  • They have one more very interesting property. They can have a parent.
  • This parent object is also consulted when a property is read.
  • That parent can also have a parent.
  • And that grandparent object is consulted too when a property is read.
  • The [[Prototype]] property keeps this reference to the parent object.
  • It’s an internal property which means that we can’t access it directly.
  • An important point to note is that the prototype chain is consulted only while reading a value.
  • It does not affect addition, updating or deletion of properties on parent objects.

Existence

Sometimes we don’t care what value a property has. We only want to know whether the given object has the given property or not.

 

There are 2 ways to know that —

  • in operator
  • hasOwnProperty

in operator

'firstName' in obj;       // => true
'middleName' in obj;      // => false 
'isPrototypeOf' in obj;   // => true
  • The syntax is String (or Symbol) in object.
  • It will evaluate to true or false depending on whether the property exists.
  • Just like Reading a property, the entire prototype chain is consulted before true or false is returned. If the property is found at any level, true is returned.

hasOwnProperty

  • It’s a function that can be accessed through an object because of prototypes.
  • It takes string key name ( or symbol) as an argument.
obj.hasOwnProperty('firstName');        
// => true
obj.hasOwnProperty('middleName');       
// => false
obj.hasOwnProperty('isPrototypeOf');    
// => false

Iteration

  • Often times you want to process the set of all values or keys and create another object with transformed values or key names.
  • Unlike arrays, you can’t simply iterate an object.
  • for-in loop
  • Object methods
    • keys
    • values
    • entries
  • Reflect.own

Popular Methods

for-in loop

for-in loop is just like a normal for loop except that it iterates on an object. You get the properties* one by one.

const obj = {
  firstName: 'Alex',
  'lastName': 'Martin', // Using string quotes
  dateOfBirth: '18th October',
  friends: [ 'Bob', 'Christine' ]
};

for (const key in obj) {
  const value = obj[key]; // Read the value 
  console.log(key, value);
}

Note: It is not recommended to use this method

  • The order of appearance of properties (may) not fixed in an object.
  • for-in loop will return all string properties. It won’t give Symbol properties.

Object methods

Object.keys()

const allProperties = Object.keys(obj); 
// => [ 'firstName', 'lastName', 'dateOfBirth', 'friends' ]
for (const property of allProperties) {
  const value = obj[property];
  console.log(property, value);
}

Object.keys() is similar to for-in loop except that it only returns the object’s own keys in an array.

Object.values()

Object.values() has similar restrictions as Object.keys(), but it returns an array of values instead of the keys.

const allValues = Object.values(obj);

// => [ 'Alex', 'Martin', '18th October', [ 'Bob', 'Christine' ] ]

Object.entries()

const allEntries = Object.entries(obj);
// => Output[ [ 'firstName', 'Alex' ],
//  [ 'lastName', 'Martin' ],
//  [ 'dateOfBirth', '18th October' ],
//  [ 'friends', [ 'Bob', 'Christine' ] ] ]

Reflect.ownKeys()

  • ownKeys return both string-based and symbol properties.
  • Note that we are using Reflect module, and not Object module.

JS Objects

By Arfat Salman