Creating and Working with Objects and Arrays

Learn common JavaScript object and array operations through beginner-friendly explanations and examples.

🎯 Introduction

This article covers the core operations for JavaScript objects and arrays: creating, accessing, modifying, and iterating over them. You will also learn practical methods for everyday data manipulation, helping you write concise, efficient code and prepare for more advanced front-end topics.


📦 Basic Object Operations

A JavaScript object stores key-value pairs. Keys are usually strings, and values can be of any type.

Creating Objects

There are several ways to create an object. Object literal syntax is the most common:

var person = {
    name: 'Alex',
    age: 20,
    city: 'Beijing',
};

You can also use new Object():

var person = new Object();
person.name = 'Alex';
person.age = 20;
person.city = 'Beijing';

Accessing Object Properties

There are two ways to access properties:

console.log(person.name); // Dot notation
console.log(person['age']); // Bracket notation
Use bracket notation when the property name comes from a variable or contains special characters or spaces.

Updating and Adding Properties

Assign a value to update a property. If the property does not exist, the assignment adds it.

person.city = 'Shanghai'; // Update an existing property
person.gender = 'male'; // Add a property

Deleting Properties

Use the delete operator to remove an object property.

delete person.age;
console.log(person);

Iterating over Objects

Use for...in to iterate over an object’s enumerable properties.

for (var key in person) {
    console.log(key, person[key]);
}
for...in includes inherited enumerable properties. To process only the object’s own properties, check with hasOwnProperty:
for (var key in person) {
    if (person.hasOwnProperty(key)) {
        console.log(key, person[key]);
    }
}

🧩 Basic Array Operations

An array is an ordered collection of values, such as numbers, strings, or other objects.

Creating Arrays

Common approaches include:

var arr1 = [10, 20, 30];
var arr2 = new Array(3); // Create an empty array with a length of 3

Accessing Array Elements

Access elements by index. Array indexes start at 0.

console.log(arr1[0]); // 10
console.log(arr1[2]); // 30

Updating Array Elements

Assign a new value directly:

arr1[1] = 25;
console.log(arr1); // [10, 25, 30]

Common Array Methods

Array methods are used frequently in front-end development. Understanding them makes everyday tasks easier.


✨ Adding and Removing Array Elements

JavaScript arrays provide several methods for adding and removing elements.

var fruits = ['apple', 'banana', 'orange'];

push: Add Elements to the End

fruits.push('grape');
console.log(fruits); // ['apple', 'banana', 'orange', 'grape']

pop: Remove and Return the Last Element

var lastFruit = fruits.pop();
console.log(lastFruit); // 'grape'
console.log(fruits); // ['apple', 'banana', 'orange']

unshift: Add Elements to the Beginning

fruits.unshift('strawberry');
console.log(fruits); // ['strawberry', 'apple', 'banana', 'orange']

shift: Remove and Return the First Element

var firstFruit = fruits.shift();
console.log(firstFruit); // 'strawberry'
console.log(fruits); // ['apple', 'banana', 'orange']

🔍 Finding and Checking Elements

indexOf: Find an Element’s Index, or Return -1 If Not Found

var pos = fruits.indexOf('banana');
console.log(pos); // 1

includes: Check Whether an Element Exists and Return a Boolean

var hasApple = fruits.includes('apple');
console.log(hasApple); // true

🔄 Iterating over Arrays

A Traditional for Loop:

for (var i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

The forEach Method:

fruits.forEach(function (item, index) {
    console.log(index, item);
});
Start by learning for and forEach. You can explore more advanced iteration methods later.

💡 Combining Objects and Arrays: Arrays of Objects

In real projects, arrays often contain objects, such as a list of users:

var users = [
    { id: 1, name: 'Taylor' },
    { id: 2, name: 'Jordan' },
    { id: 3, name: 'Casey' },
];

Finding an Object

To find the user whose id is 2, use a loop:

var user = null;
for (var i = 0; i < users.length; i++) {
    if (users[i].id === 2) {
        user = users[i];
        break;
    }
}
console.log(user); // { id: 2, name: 'Jordan' }
This straightforward approach is easy for beginners to follow.

Updating an Object

Change the name of the user whose id is 3:

for (var i = 0; i < users.length; i++) {
    if (users[i].id === 3) {
        users[i].name = 'Robin';
        break;
    }
}
console.log(users);

🔧 Practical Tips

Combining Arrays

Use concat to combine two arrays:

var arrA = [1, 2];
var arrB = [3, 4];
var combined = arrA.concat(arrB);
console.log(combined); // [1, 2, 3, 4]

Converting an Array to a String

Use join to combine array elements into a string with a specified separator:

var str = fruits.join(',');
console.log(str); // apple,banana,orange

❓ Knowledge Check

Q1: How do you add a property to an object dynamically? Assign a value to a property that does not yet exist, for example obj.newProp = value;.

Q2: How do pop and shift differ?pop removes and returns the last element; shift removes and returns the first.

Q3: How do you avoid inherited properties when iterating over an object? Use hasOwnProperty to check whether each property belongs to the object itself.


🧪 Exercises

Complete these two tasks using the starter code:

    1. Add a new student object with name and score properties to the end of students.
    1. Iterate over students and print every student’s name and score.
var students = [
    { name: 'Sam', score: 90 },
    { name: 'Chris', score: 85 },
];

// Add your code here

🎉 You now know how to create, iterate over, and modify JavaScript objects and arrays, along with several useful methods. Keep practicing to see how flexible these data structures can be!