Skywalker
Skywalker

Reputation: 5194

Object Reflection & Enumeration - JavaScript

I am currently reading "JavaScript The Good Parts" by Douglas Rockford and I came across the following two topics:

  1. Reflection
  2. Enumeration

According to the book:

It is easy to inspect an object to determine what properties it has by attempting to retrieve the properties and examining the values obtained.The typeof operator can be very helpful in determining the type of a property.

Although I understand what is being said, that we can use object reflection to basically view all the properties and values it contains. Something like reading ingredients from the back of product to see what is it exactly made of.

My Question is Why and How? Why would I need to use object Reflection, in what scenario and what are advantages of using it and How does Enumeration connect with? What is the link between Reflection & Enumeration?

Thanks in advance.

Upvotes: 3

Views: 177

Answers (1)

Schemiii
Schemiii

Reputation: 366

In JS objects are often created in a very dynamic way. Have a look at the following snippet.

An array of dynamic created Objects.

    var persons = [{
      name: "Peter",
      age: 20
    },{
      name: "Fox",
      ages: "21"},
      ,{
      name: "Fox",
      age: "21"}
    ]

An object which is used as a filter.

var types={
    name: "string",
    age:"number"
}

Each object in persons is checked if it has the property name and age. Object.keys returns an Array of the objects properties.

In other languages this is way more complex than this one liner.

console.log(persons.filter(function(person){
  return Object.keys(person).filter(function(property){
    return types[property] && typeof person[property] === types[property];
  }).length === requiredProps.length;
}));

Furthermore the required type - string and number - is also checked.

But why ? There are different scenarios e.g. within a web application where you need to check if a user has specified some required input. And in programming you very often need to do sth with objects in an array. Therefore the Array functions filter, reduce, map are heavily used to manipulate some input for some output. Wether for functions or for some server APIs.

Best regards

Upvotes: 1

Related Questions