0

I'm having a problem with my Javascript function, I'm not understanding something, just looking for some clarity.

I have a function:

function Test (array) {
    if (array === []) {
        return "the array is empty";
    } else {
    return array;
}

When I pass this function an empty array, it returns the empty array, completely skipping the first part of my if statement (this is the part I'm not understanding, why is it skipping that part? My understanding is that it would return my string statement at that point since the array I pass it, is in fact empty. If I remove the else statement, it returns "undefined".

NOTE! : I am aware that the solution to this problem is to set my "if" statement to compare the length of the array I pass it.

ex:

function Test (array) {
    if (array.length === 0) {
        return "the array is empty";
    } else {
    return array;
}

I'm just still not understanding why the first one doesn't work, and would really appreciate an explanation.

j08691
  • 204,283
  • 31
  • 260
  • 272
Fabian
  • 59
  • 9

1 Answers1

3

When you compare two objects in JavaScript, the comparison is asking "Are these objects the same object?", not "Are these objects identical?".

You are comparing two different empty arrays.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335