ArcGIS JavaScript API – Solving TypeError: featureLayer.fields is Undefined

arcgis-javascript-apitypeerror

When working with the ArcGIS API for JavaScript, I have been getting an error in FireBug when trying to execute the following script:

var featLayerURL = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/TaxParcel/AssessorsLiveLayers/MapServer/1";
var featLayer = new esri.layers.FeatureLayer(featLayerURL);
alert(featLayer.fields.length);

The error returned is:

TypeError: featLayer.fields is undefined.

At first I thought it was something wrong with one of my server's layers, but after using that sample server and getting the same error, I'm sure there is something else wrong.

Here is a link to the REST response: Layer: Recorded Tax Parcel Sales (ID: 1).

Best Answer

This is basically a timing issue. I recreated your sample and it appears that the response has not returned yet so when you immediately check the length you get the error. I moved the alert to its own function and called that function after the page had been initialized and everything worked as expected. If you want data other than the id then you will need to add an option to the constructor that returns all of the fields.

var featLayer = new esri.layers.FeatureLayer(featLayerURL, {
                    outFields: ["*"]
                });