how to properly check if an object is array in javascript

April 2, 2024

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui(2024-04-02 22:50:26 +0000). how to properly check if an object is array in javascript. https://borui/blog/2024-04-02-en-how-to-properly-check-whether-is-array.
@misc{
  borui2024,
  author = {borui},
  title = {how to properly check if an object is array in javascript},
  year = {2024},
  publisher = {borui's blog},
  journal = {borui's blog},
  url={https://borui/blog/2024-04-02-en-how-to-properly-check-whether-is-array}
}

proper way

The Array.isArray() static method determines whether the passed value is an Array.

  1. Array.isArray(). (n.d.). MDN docs. Retrieved April 02, 2024, from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

why the question since it is so easy

Because I have tried something dangerous by checking whether something is iteratable instead, as this would recurr unexpected results, since strings are also iteratable.

  1. Tomas Kulich. (Sep 12, 2015). The proper way to check for iterability is as follows: ... Why this works (iterable protocol in depth): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols Since we are talking about for..of, I assume, we are in ES6 mindset. Also, don't be surprised that this function returns true if obj is a string, as strings iterate over their characters.. [Answer]. stackoverflow. https://stackoverflow.com/questions/18884249/checking-whether-something-is-iterable/32538867