Avatar ·

How to check if an object is an array in JavaScript?

Hi everyone! I just started learning JavaScript and encountered a confusing situation. I need to check if a variable is an array, but I'm getting strange results. Here's the code: ```javascript let arr = [1, 2, 3]; let obj = {name: "John"}; let str = "hello"; console.log(typeof arr); // "object" console.log(typeof obj); // "object" console.log(typeof str); // "string" ``` The `typeof` operator returns "object" for both an array and a regular object. Because of this, I can't distinguish an array from an object. I tried checking with `arr instanceof Array` — it seems to work, but I've heard that this method can fail if the array was created in a different frame or iframe. I've also seen that some people use `Array.isArray()`, but I don't understand how this method is better or worse.