Skip to main content

Different data types in an array

Yes - in JavaScript you can store different data types in one array.

This is one of the key features of the language: an array is not typed, so its elements can be of any type - numbers, strings, objects, functions, and even other arrays.

Example:

javascript
const mixed = [ 42, // number "hello", // string true, // boolean value { 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"

Why this is possible

  • In JS an array is an object, where indexes are keys ("0", "1", "2", ...), and the values can be of any type.
  • JavaScript is a dynamically typed language, so the type of an element is not fixed when the array is created.

But worth remembering:

  • Although this is allowed, for code convenience and readability it is usually best to store homogeneous data (for example, a list of numbers or a list of objects).
  • If an array has many different types, working with it becomes harder.

In short:

QuestionAnswer
Can different types be stored?Yes
Why?An array is an object, JS is not typed
Is it recommended?Only if it is genuinely needed
Example[1, "text", true, {id: 1}, [5,6], ()=>{}]

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.