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

1 Answer 1

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! :)

Sign up to request clarification or add additional context in comments.

1 Comment

Actually the allowedNull is not required in my code, as its empty and not in use. Some misinterpretations. :| Anyways thanks for the help ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.