ReynierPM
ReynierPM

Reputation: 18660

Is not `.length` the right way to check whether an array is empty or not in Javascript?

I have the following AJAX call:

$('#fileupload').show().fileupload({
    url: '/upload',
    type: "POST",
    cache: false,
    dataType: 'json',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    done: function (e, data) {
        var error_msg = $("#load_error_msg");

        error_msg.html('');

        if (data.result.error.length > 0) {
            // process errors messages here 
        } else {
            // do something else
        }
    },
})

The upload method on the backend return a JSON like the following:

{
  "error": {
    "fileUploadErrorIniSize": "File '' exceeds the defined ini size"
  }
}

The code is bypassing this checking data.result.error.length and going always trough the else condition.

I am confused at this point: is not .length the right way to check whether an array is empty or not in Javascript? If it's not which is the right way?

Upvotes: 0

Views: 63

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

It's not an array, it's a plain object. Plain objects don't have a length property by default.

You can use Object.keys(data.result.error).length to see if it has any own, enumerable properties, which your example will have.

E.g., assuming data.result really points to that data structure, then:

if (Object.keys(data.result.error).length > 0) {

If there's any possibility that data.result won't have an error property at all, you'll want to guard against that:

if (data.result.error && Object.keys(data.result.error).length > 0) {

But if you know it'll always be there (just sometimes empty), there's no need.

Upvotes: 4

Related Questions