PROGRAMMING-CONCEPTS

Array: Definition, Syntax, and Examples

An array is a data structure that stores multiple values in an ordered collection. Each value in an array is called an element, and every element has an index that indicates its position.

Arrays make it possible to group related values under one name—whether they’re numbers, strings, or objects—and work with them efficiently.


How Arrays Work

An array groups several variables into one organized structure. Instead of writing separate variables like item1, item2, and item3, you can store them together:

numbers = [10, 20, 30, 40]

Here, numbers[0] is 10, and numbers[3] is 40.

Arrays use zero-based indexing, meaning the first element starts at index 0. This structure allows for quick access, looping, sorting, and filtering of data.


Array Syntax in Different Languages

Although syntax differs between languages, arrays follow the same core principle: store, access, and manipulate a list of elements.

Python (Lists)

Python uses lists, which behave like dynamic arrays.

fruits = ["apple", "banana", "cherry"]
print(fruits[1])  # banana
fruits.append("orange")

Lists can hold mixed data types and grow or shrink dynamically.


JavaScript / TypeScript

In JavaScript, arrays are essential for handling collections of data.

const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // apple
fruits.push("orange");

TypeScript adds type safety:

const numbers: number[] = [1, 2, 3, 4];

These arrays come with many built-in methods for transformation and filtering.


Swift

var fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits[2])

Swift arrays are typed collections—each element must match the declared data type.

var numbers: [Int] = [1, 2, 3, 4]

SQL

SQL doesn’t use arrays in standard syntax, but certain databases like PostgreSQL allow them.

SELECT UNNEST(ARRAY['red', 'green', 'blue']);

Arrays in SQL help store multiple values in a single column and can be “unpacked” for analysis.


Common Use Cases

Arrays are used anywhere you need to store or process multiple pieces of related data.

1. Iterating Through Data (Python)

scores = [85, 92, 78]
for score in scores:
    print("Score:", score)

Loops let you apply the same operation to every element.


2. Dynamic Web Content (JavaScript / React)

Arrays power data-driven UIs.

const tasks = ["Read", "Write", "Code"];
function TaskList() {
  return (
    <ul>
      {tasks.map((task, index) => <li key={index}>{task}</li>)}
    </ul>
  );
}

Here, .map() transforms array items into list elements on a webpage.


3. Sorting and Filtering (TypeScript)

const numbers = [10, 5, 8, 20];
const sorted = numbers.sort((a, b) => a - b);
const filtered = numbers.filter(num => num > 8);

Arrays make it easy to clean, sort, and process data efficiently.


4. Fixed-Length Collections (Swift)

let highScores = [1200, 980, 1500]
for score in highScores {
    print("High Score:", score)
}

Swift arrays work well for collections with predictable sizes.


Array Indexing and Access

Each element in an array is accessed using its index:

const colors = ["red", "green", "blue"];
console.log(colors[1]); // green
colors[1] = "yellow";   // update element

Accessing an out-of-range index (like colors[10]) usually returns undefined or triggers an error, depending on the language.


Useful Array Methods

Modern languages provide built-in array methods that simplify manipulation:

  • push() / append(): Add a new element
  • pop() / remove(): Delete the last element
  • slice() / splice(): Copy or edit parts of an array
  • map(): Transform each element
  • filter(): Keep only matching elements
  • reduce(): Combine all elements into one result

Example in JavaScript:

const prices = [5, 10, 15];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 30

Arrays vs. Objects

Arrays and objects both store data but serve different purposes.

Example:

// Array
const users = ["Luna", "Alex", "Mia"];

// Object
const user = { name: "Luna", age: 28 };

Arrays are for ordered lists of similar items; objects describe an individual item’s properties.


Common Array Mistakes

Even experienced developers sometimes make small array-related errors:

  • Using <= instead of < in loops, causing off-by-one issues.
  • Forgetting arrays start at index 0.
  • Modifying an array while looping through it.
  • Mixing data types in typed languages.
  • Expecting standard SQL databases to support arrays.

Careful indexing and consistency prevent these issues.


Best Practices

To write cleaner and more efficient code with arrays:

  • Use descriptive names (students is clearer than arr).
  • Keep arrays uniform by storing one type of data.
  • Check array length before accessing elements.
  • Prefer array methods over manual loops.
  • Avoid mutation when possible—return new arrays instead.

Clear structure and consistent naming make array operations easier to maintain.


Summary

An array is an ordered list of elements that allows programs to store and manipulate multiple values efficiently. It helps organize data, simplify loops, and make logic more expressive in languages like Python, JavaScript, TypeScript, Swift, SQL, and React.

Arrays form the foundation for more advanced data structures such as lists, sets, and matrices—making them essential for anyone learning computer programming.

Learn to Code for Free
Start learning now
button icon
To advance beyond this tutorial and learn to code by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

Reach your coding goals faster