Distinguishing between arrays and objects in JavaScript
Contrary to what you’d expect, typeof [1, 2, 3]
returns 'object'
in JS.
If you need to distinguish between the two, for cases like dynamic component rendering from JSON in React, you’ll need to use the following approach:
javascript
1const variable = [1, 2, 3];
2
3if (Array.isArray(variable)) {
4 console.log('variable is an array');
5} else if (typeof variable === 'object') {
6 console.log('variable is an object');
7}
For the dynamic rendering case, it’s worth remembering that typeof null
also outputs 'object'
and might need to be handled as well.