0

I'm trying to modify this javascript for retrieving place information but I cannot figure out what the if statement is evaluating in the example here: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform

The specific if statement I don't understand what is being evaluated is:

if (componentForm[addressType]) {
        var val = place.address_components[i][componentForm[addressType]];
        document.getElementById(addressType).value = val;
      }
1
  • All your answers are correct. My problem was understanding the remaining of the code. From what I understand now, it was checking if there was a short_name or long_name in the componentForm of the addressType of the place.address_components. Commented Sep 8, 2018 at 14:52

3 Answers 3

3

This will check if componentForm[addressType] is not undefined, null, empty string, 0, NaN nor false.

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

Comments

1

componentForm is an object made at the top of the <script> block:

var componentForm = {
    street_number: 'short_name',
    route: 'long_name',
    locality: 'long_name',
    administrative_area_level_1: 'short_name',
    country: 'long_name',
    postal_code: 'short_name'
};

To access properties in a JS object, you can use the Array notation when needing a dynamic way to access properties - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#Syntax

The if statement is testing whether the componentForm object hasOwnProperty() or any prototype whose key name is equal to the string value inside addressType and if that is true, then grabs that value using the resulting value from componentForm as the property accessor into the place.address_components[i] object.

place.address_components[i][componentForm[addressType]]

place - object address_components - array i - integer componentForm - object addressType - string

Comments

1

if (componentForm[addressType]) {

Evaluates if componentForm[addressType] is existing

Here are some possibilities of if condition failing

        0
        null
        ""
        ''
       [].length
       {}.length
       undefined
       false

Here are some cases of if condition successful

"string"
"0"
" "
' '
[]
{}
true

You can console.log(componentForm[addressType]) or alert(componentForm[addressType]) and check which of the above mentioned scenarios are matching.

Comments

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.