0

I went through some JS code last day, but I couldn't understand. Here is the code

var data = {
     name : 'Mr John',
     age : '29',
     location : 'New York',
     profession : 'Accoutant'
};

var allowedNull = [];

for (var i in data) {
     if (!data[i])
     {

          if (allowedNull.indexOf(i) < 0)
          {
               console.log('Empty');
          }
     }
}

The script actually prints "Empty" in console if the data has an empty property. I just wanted know, how it works by calling indexOf on allowedNull . Can somebody explain how this works.

Fiddle : Check

noob
  • 641
  • 1
  • 6
  • 21

1 Answers1

2

first of all the indexOf(i) method returns the first index at which a given element can be found in the array, or -1 if it is not present. In this case the flow is:

//loop over data object

for (var i in data) {

//if the current property is empty/undefined
 if (!data[i])
 {
      //and if this property is not present inside the allowedNull array
      if (allowedNull.indexOf(i) < 0)
      {
           // print empty
           console.log('Empty');
      }
 }
}

If you try to add in the data object the property test : '' you'll get printed in the console Empty but if you add test inside the allowedNull array var allowedNull = ['test'] nothing will be printed.

Hope this can help! :)

Pierfrancesco
  • 518
  • 6
  • 18
  • 2
    Actually the allowedNull is not required in my code, as its empty and not in use. Some misinterpretations. :| Anyways thanks for the help ;) – noob Sep 26 '15 at 08:04