Glademist
Glademist

Reputation: 57

Can not check emptiness of array at index in Javascript

I have an array in Javascript. It looks like the one below.

source_array=[["A","B","C"],["A","B","C"],["A","B","C"]];

I create it by source_array.push(anotherArray). During the running of my code i remove entries from the indexes one by one by source_array[1].splice(0,1). So from [["A","B","C"],["A","B","C"],["A","B","C"]] i expect to get [["A","B","C"],["B","C"],["A","B","C"]];

If i do it enough times i should end up with [["A","B","C"],[],["A","B","C"]].

How to properly check if source_array[1] is now empty? It doesnt seem to work for me.

If (source_array[1] == undefined) this turns out FALSE instead of TRUE. It gives out FALSE only after i am done removing the items. It works well if i check for source_array[2] in a source_array[["A","B","C"],["A","B","C"]]

I think i tried everything i found online.

I feel it will be something basic, but i am an amateour and this...beats me.

Upvotes: 0

Views: 36

Answers (1)

a3gis
a3gis

Reputation: 51

While the array is empty, it's not undefined.

Always check the array's length property to determine whether a targeted array is empty.

Thus:

let arr = [];
let arr2 = ['foo', 'bar'];

arr.length === 0;  // true, empty
arr2.length === 0; // false, populated

Upvotes: 1

Related Questions