DEV Community

Yuya Hirano
Yuya Hirano

Posted on

Don't misunderstand the Array.【JavaScript】

When I was building my app, I tried to use an empty array for an IF statement.
I'd like to share with you all the misunderstanding that occurred there.

Example

const arr = [];

if (arr) {
    console.log("True");
} else {
    console.log("False");
}

// result
True
Enter fullscreen mode Exit fullscreen mode

I expected "False" that return value that statement.
However, It returned "True".

Why?

I read developer references again.
Truthy

As it turns out, an empty array is used as a true value.

what do we do now?

const arr = [];

if (arr**.length**) {
    console.log("True");
} else {
    console.log("False");
}

// result
False
Enter fullscreen mode Exit fullscreen mode

The answer is simple. I'll give it to it using ".length".

In addition, check the object.

const obj = {};

if (obj) {
    console.log("True");
} else {
    console.log("False");
}

// result
True
Enter fullscreen mode Exit fullscreen mode

object cannot use "length' property simply.
You can use "keys" property instead of it.

const obj = {};  // 空のオブジェクト

if (Object.keys(obj).length) {
    console.log("True");
} else {
    console.log("False");
}

// result
Bye
Enter fullscreen mode Exit fullscreen mode

Let's take another look at the arrays and objects that we use somewhat on a daily basis to avoid misunderstandings.
If there are any errors in this article or if you know of a better way,
I would appreciate your comments.
If you like this article, please give me a like button.

Top comments (0)