TutorialsJSArrays & Objects
Share:

Arrays & Objects

advanced

Part of JavaScript in the Browser

Theory

Arrays and objects are the two primary data structures in JavaScript for storing and organizing data.

Arrays are ordered, zero-indexed collections of values. They can hold elements of any type — numbers, strings, objects, or even other arrays. Arrays are created with square brackets [] or the new Array() constructor.

let fruits = ["apple", "banana", "cherry"];
let mixed = [1, "hello", true, null, { name: "John" }];

Access elements using their index: fruits[0] returns "apple". The length property returns the number of elements.

JavaScript arrays have powerful methods for manipulation:

  • Mutating methods: push() (add to end), pop() (remove from end), shift() (remove from start), unshift() (add to start), splice() (add/remove anywhere), reverse(), sort()
  • Non-mutating methods: concat() (merge arrays), slice() (extract portion), join() (convert to string), indexOf() (find index), includes() (check existence)
  • Iteration methods: forEach() (loop), map() (transform each element), filter() (keep matching elements), reduce() (accumulate values), find() (get first match), some() (any match), every() (all match)

Objects are collections of key-value pairs. Keys are strings (or Symbols), and values can be any type. Objects are created with curly braces {}.

let person = {
  name: "Alice",
  age: 30,
  greet() {
    return `Hi, I'm ${this.name}`;
  }
};

Access properties with dot notation (person.name) or bracket notation (person["name"]). Bracket notation is necessary for computed properties or keys with spaces.

The this keyword refers to the object the method is called on. Its value depends on how the function is called — not where it is defined. Arrow functions do not have their own this; they inherit it from the surrounding scope.

Destructuring provides a concise way to extract values from arrays and objects:

const [first, second] = ["a", "b", "c"];
const { name, age } = { name: "Bob", age: 25 };

The spread operator (...) expands iterables into individual elements. It's useful for copying arrays/objects and merging them.

Practical Examples

Example 1: Array Methods in Action
javascript
Example 2: Objects and Destructuring
javascript

Exercises

Shopping List Manager

easy

Create an array of shopping items: 'milk', 'bread', 'eggs'. Add 'butter' to the end, add 'apples' to the beginning, remove the last item, and print the final array and its length.

Starter Code:

let shoppingList = ['milk', 'bread', 'eggs'];\n// Your code here

Expected Output:

['apples', 'milk', 'bread']\n3

Transform and Filter Scores

medium

Given an array of test scores: [45, 78, 92, 55, 88, 63]. Use filter() to get scores >= 70, use map() to add 5 bonus points to each passing score, and use reduce() to calculate the average of the final scores.

Starter Code:

const scores = [45, 78, 92, 55, 88, 63];\n// Your code here

Expected Output:

Passing scores with bonus: [83, 97, 93]\nAverage: 91

User Profile Builder

medium

Create an object representing a user with properties: firstName, lastName, email, and an address object (with city and country). Add a method 'fullName' that returns the full name. Destructure the email and city into variables.

Starter Code:

// Create your user object here

Expected Output:

John Doe\njohn@example.com lives in New York

Mini Quiz

Mini Quiz

Mini Project

Mini Project: Student Gradebook System

Build a gradebook system using arrays and objects. Each student has a name, ID, and array of scores. The system should calculate averages, find top performers, and generate reports.

Requirements:

    Bonus Challenge

    Add a method to each student object that returns their letter grade based on average.