Mixed data types in one array
Yes, a single JavaScript array can store data of different types. This is one of the language's defining traits: an array is untyped, so its elements can be numbers, strings, objects, functions and even other arrays.
Theory
TL;DR
- A JavaScript array is untyped: there are no restrictions on the types of its elements.
- The reason is that an array is an object where indexes are the keys (
"0","1","2") and the values can be anything. - JavaScript is dynamically typed, so an element's type is not fixed when the array is created.
- Being possible does not make it advisable: homogeneous data is usually the better choice.
- For heterogeneous data the more natural structure is an object with named fields.
- If you really need a mixed array, check each element's type before processing it.
Quick example
const mixed = [
42, // number
'hello', // string
true, // boolean
{ name: 'Tim' }, // object
[1, 2, 3], // nested array
function () { return 'JS'; } // function
];
console.log(mixed[0]); // 42
console.log(mixed[1]); // "hello"
console.log(mixed[3].name); // "Tim"
console.log(mixed[4][1]); // 2
console.log(mixed[5]()); // "JS"Every element lives at its own index and behaves according to its own type: you reach into the object with dot notation, into the nested array with a second index, and you call the function with parentheses.
Why this works
- In JavaScript an array is an object whose indexes are the keys (
"0","1","2", ...), and whose values may be of any type. - JavaScript is a dynamically typed language, so an element's type is not fixed at the moment the array is created.
That is easy to verify: you can change types after creation and the array will not object.
const items = [1, 2, 3];
items[0] = 'now a string';
items.push(null, undefined, Symbol('id'));
console.log(items.length); // 6What to keep in mind
- Even though it is allowed, for convenience and readability people usually keep homogeneous data in an array, for example a list of numbers or a list of objects.
- When an array holds many different types, working with it gets harder:
map,filter,sortandreduceall have to be wrapped in type checks. - A homogeneous array is also faster: engines optimise arrays whose elements are all of one kind, and mixing types moves the array to a slower internal representation.
- When the elements differ in meaning rather than in type, prefer an object with named fields over an array:
{ id: 1, title: 'text', active: true }.
Handling a mixed array safely
If you do need a mixed array, say it holds parsed form data or values from an external response, check the type before processing.
const mixed = [42, 'hello', true, { name: 'Tim' }, [1, 2, 3]];
const numbers = mixed.filter((item) => typeof item === 'number');
const arrays = mixed.filter((item) => Array.isArray(item));
console.log(numbers); // [42]
console.log(arrays); // [[1, 2, 3]]Remember that typeof does not distinguish an array from an object (both give "object"), so arrays need Array.isArray().
In short
| Question | Answer |
|---|---|
| Can you store different types? | Yes |
| Why? | An array is an object, and JavaScript is dynamically typed |
| Is it recommended? | Only when you genuinely need it |
| Example | [1, 'text', true, { id: 1 }, [5, 6], () => {}] |
Common mistakes
- Calling methods without checking the type.
mixed.map((x) => x.toUpperCase())throws on the first number or onnull. - Sorting a mixed array.
sort()without a comparator compares string representations, so[10, 'a', true].sort()produces a surprising order. - Confusing an array with an object inside the array.
typeofreturns"object"for a nested array, so you needArray.isArray(item). - Storing the heterogeneous fields of one record as an array.
['Tim', 25, true]reads worse than{ name: 'Tim', age: 25, active: true }and breaks as soon as the order changes. - Expecting the same behaviour in TypeScript. There arrays are typed, and mixed values force you to declare a union or a tuple:
(number | string)[]or[string, number].
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.