Arrays & objects in React JS
Course: React JS Training
Topic: Arrays & objects
Course Link: React JS Training
Demo Link: Register for a Course Demo
1. Why Arrays and Objects Matter
A single variable holds a single value. That works for one student's age, but real applications almost never deal with single values. A shopping cart holds many products, a class register holds many students, and each product or student itself carries several details: a name, a price, an email address. JavaScript gives you two structures for exactly these situations: arrays for ordered lists of values, and objects for labelled collections of related values.
These two structures matter even more because of where this course is heading. React is built on data flowing between components, and that data is almost always shaped as arrays and objects. When you later fetch information from a server, the JSON that arrives is nothing more than nested arrays and objects. Master them here and the React modules will feel natural; skip them and everything afterwards feels like magic.
2. What Exactly Are Arrays and Objects?
An array: a list under one name
An array is an ordered list of values stored under a single variable name. Instead of creating three variables for three test marks, you create one array holding all three, in order:
let marks = [78, 92, 85];
Each value inside is called an element. The order matters: 78 comes first, then 92, then 85. An array can hold any type of value — numbers, strings, booleans, even other arrays and objects — and it can grow or shrink while the program runs.
An object: labelled details of one thing
An object is a collection of labelled values that together describe one thing. Where an array is "a list of marks", an object is "a student": a name, an age, a course. Each label is called a key, the data attached to it is the value, and the pair together is a property:
let student = {
name: "Aisha",
age: 21,
course: "React JS"
};
Read this as: the student's name is "Aisha", the student's age is 21, the student's course is "React JS". Unlike an array, order is not the point here — you reach values by name, not by position.
The one-line summary
Use an array when you have many similar things and their order matters. Use an object when you have one thing with several named details.
3. Key Terms at a Glance
You will meet these words on every page of this course, so fix them in your mind now. The table separates terms that belong to arrays from terms that belong to objects, plus a few that apply to both.
| Term | Belongs to | Meaning in plain words |
| Element | Array | One value stored inside the array |
| Index | Array | The position number of an element, starting at 0 |
| length | Array | A built-in property reporting how many elements the array holds |
| Key | Object | The label attached to a value, also called a property name |
| Value | Both | The actual data stored under an index or a key |
| Property | Object | One key-value pair taken together |
| Method | Both | A function attached to the array or object, such as push() |
| Mutable | Both | Can be changed after creation — arrays and objects both are |
| Nested | Both | An array inside an object, an object inside an array, and so on |
Two of these deserve an early warning. Mutable means you can change an array or object after creating it, unlike a number or a string, which you replace wholesale. Nested means structures inside structures, which is where beginners most often get lost, so this page builds up to nesting gently.
4. Creating Arrays: Syntax and Rules
The array literal
The normal, recommended way to create an array is the array literal: square brackets containing values separated by commas.
// An array of numbers
let temperatures = [29, 31, 27, 30];
// An array of strings
let fruits = ["mango", "banana", "papaya"];
// An empty array, ready to be filled later
let cart = [];
// Mixed types are allowed
let mixed = ["Aisha", 21, true];
Whitespace and line breaks mean nothing to JavaScript, so long arrays are usually written across several lines with one element per line — this is the style you will see in real projects and in React components.
Index positions and length
let fruits = ["mango", "banana", "papaya"];
console.log(fruits[0]); // "mango" (first element)
console.log(fruits[2]); // "papaya" (third element)
console.log(fruits.length); // 3
length is a property that every array carries automatically. It always tells you how many elements are present, and it updates itself as the array grows or shrinks. Because counting starts at 0, the last valid index is always length - 1: an array of 3 elements has indexes 0, 1 and 2.
A note on new Array()
You may also see arrays created with new Array(3). Avoid this as a beginner: new Array(3) does not create the array [3] — it creates an empty array of length 3. The literal form does exactly what you write, so stick with square brackets.
5. Reading and Changing Array Elements
Reading with bracket notation
Put the index in square brackets immediately after the array name:
let colours = ["red", "green", "blue"];
console.log(colours[0]); // "red"
console.log(colours[1]); // "green"
// An index that does not exist gives undefined, not an error
console.log(colours[9]); // undefined
Reading a position beyond the end of the array quietly returns undefined. This is worth remembering when debugging: if you see undefined where you expected a value, suspect a wrong index.
Updating an element
colours[1] = "yellow";
console.log(colours); // ["red", "yellow", "blue"]
Assignment to an existing index replaces the value in place. Assignment to an index beyond the end creates that index and leaves gaps of undefined in between — usually a mistake, so update only indexes that already exist and use the methods in the next section to add new values.
Reaching the last element
let last = colours[colours.length - 1];
console.log(last); // "blue"
This pattern appears everywhere in real code, because you rarely know an array's length in advance. length - 1 always points at the final element, whatever the size.
6. Adding and Removing Elements Step by Step
Four built-in methods handle adding and removing at the two ends of an array. They are the workhorses of everyday JavaScript.
| Method | What it does | What it returns |
push(value) | Adds a value at the end | The new length |
pop() | Removes the last value | The removed value |
unshift(value) | Adds a value at the start | The new length |
shift() | Removes the first value | The removed value |
Watching an array change
let queue = ["Ali"];
queue.push("Bhavna"); // ["Ali", "Bhavna"]
queue.push("Chirag"); // ["Ali", "Bhavna", "Chirag"]
queue.shift(); // ["Bhavna", "Chirag"] ("Ali" left)
queue.unshift("Deepa"); // ["Deepa", "Bhavna", "Chirag"]
queue.pop(); // ["Deepa", "Bhavna"] ("Chirag" left)
Step through the comments one line at a time and picture the array after each call. A useful memory trick: push and pop act on the end of the array, while shift and unshift act on the start — "shift" moves every remaining element back by one position, which is where the name comes from.
Inserting in the middle with splice
The four methods above only touch the ends. For any position in the middle, use splice(startIndex, deleteCount, item1, item2, ...), which removes and/or inserts elements at the spot you name:
let days = ["Mon", "Wed", "Thu"];
// At index 1, delete 0 items, insert "Tue"
days.splice(1, 0, "Tue");
console.log(days); // ["Mon", "Tue", "Wed", "Thu"]
With a delete count of 0, splice purely inserts. Give it a delete count of 1 or more and it also removes that many elements starting at the index. Splice changes the original array, which the next section contrasts with its gentler cousin.
7. Everyday Array Methods Worth Memorising
These methods answer the questions beginners ask most often about a list: is this value in it, where is it, and how do I combine or copy it?
let cities = ["Pune", "Delhi", "Mumbai", "Delhi"];
// Is a value present anywhere in the array?
console.log(cities.includes("Delhi")); // true
// Where is it? First match, or -1 if absent
console.log(cities.indexOf("Mumbai")); // 2
console.log(cities.indexOf("Surat")); // -1
// Join every element into one string
console.log(cities.join(" | ")); // "Pune | Delhi | Mumbai | Delhi"
// Copy a portion without touching the original
let firstTwo = cities.slice(0, 2);
console.log(firstTwo); // ["Pune", "Delhi"]
// Merge arrays into a brand-new array
let more = ["Nagpur"];
let all = cities.concat(more);
console.log(all); // ["Pune", "Delhi", "Mumbai", "Delhi", "Nagpur"]
Two habits to build here. First, includes and indexOf are the standard ways to check whether a list contains something — indexOf returning -1 is the classic signal for "not found". Second, note the pair slice and splice: slice copies and leaves the original untouched, while splice cuts into the original. The similar names confuse everyone at first, so read them carefully whenever you meet them.
8. Looping Through Arrays
The classic for loop
When you need the position number as well as the value, use a for loop that counts from 0 up to (but not including) the length:
let marks = [78, 92, 85];
let total = 0;
for (let i = 0; i < marks.length; i++) {
total = total + marks[i];
}
console.log(total); // 255
Notice the condition i < marks.length — strictly less than, because the last valid index is length minus one. Writing i <= marks.length is the classic off-by-one mistake: the final pass reads marks[3], which does not exist, and quietly adds undefined to the total.
The for...of loop
When you do not need the index, for...of hands you each element directly and reads far more naturally:
let fruits = ["mango", "banana", "papaya"];
for (let fruit of fruits) {
console.log(fruit);
}
// mango
// banana
// papaya
The forEach method
Arrays also carry a built-in method called forEach, which runs a function once for every element, passing that element in as an argument:
fruits.forEach(function (fruit) {
console.log("I like " + fruit);
});
The shorter arrow-function way of writing that callback belongs to the Modern JavaScript module later in this course; the behaviour is identical either way. For now, choose for...of or forEach whenever you simply want to visit every element, and the counted for loop when the position itself matters.
9. Creating Objects: Syntax and Rules
The object literal
The everyday way to create an object is the object literal: curly braces containing key: value pairs separated by commas.
let product = {
name: "Keyboard",
price: 1500,
inStock: true
};
Keys are written without quotes when they are simple words; values can be any type — string, number, boolean, array, even another object. A trailing comma after the last property is allowed and common in real code, because it makes adding the next property a one-line change.
Dot notation vs bracket notation
| Syntax | Example | Use it when |
| Dot notation | product.price | The key is a simple word, known while you write the code |
| Bracket notation | product["price"] | The key contains spaces or symbols, or is stored in a variable |
console.log(product.name); // "Keyboard"
console.log(product["price"]); // 1500
let field = "inStock";
console.log(product[field]); // true — variable inside brackets
A classic beginner mistake is writing product[field] as product["field"]. With quotes, you ask for a key literally named "field"; without quotes, JavaScript looks up the variable and uses its value as the key. Dot notation is your default; reach for brackets only when the two conditions in the table apply.
10. Reading, Adding, Updating and Deleting Properties
Adding and updating follow one rule
let student = {
name: "Ravi",
age: 22
};
student.course = "React JS"; // add a new property
student.age = 23; // update an existing one
student["attendance"] = "95%"; // add via brackets
console.log(student);
// { name: "Ravi", age: 23, course: "React JS", attendance: "95%" }
Both notations behave identically for this purpose: they create the property if it does not exist and overwrite it if it does. That single rule covers adding and updating, which is why objects feel so flexible once you get used to them.
Checking for a key and deleting one
console.log("age" in student); // true
console.log(student.email); // undefined — key absent, no error
delete student.attendance;
console.log("attendance" in student); // false
Reading a missing key quietly gives undefined rather than an error, and the in operator checks whether a key exists at all. The delete operator removes a property from the object; it is used far less often than adding and updating, but you should recognise it when you see it in other people's code.
Realistic example: a profile that grows
let profile = { username: "priya_k" };
profile.fullName = "Priya Kulkarni";
profile.skills = ["HTML", "CSS", "JavaScript"];
console.log(profile.skills[1]); // "CSS"
Notice the last line: an object property can hold an array, and you can chain the access — first the property with a dot, then the array index in brackets. Chaining like this is the everyday grammar of JavaScript data.
11. Objects Can Hold Functions: Methods
When a property's value is a function, that property is called a method. Methods let an object carry its own behaviour alongside its data, instead of keeping the data in one place and the logic somewhere else.
let account = {
owner: "Meera",
balance: 5000,
deposit: function (amount) {
account.balance = account.balance + amount;
},
describe: function () {
return this.owner + " has balance " + this.balance;
}
};
account.deposit(2000);
console.log(account.describe()); // "Meera has balance 7000"
Inside a method, the keyword this refers to the object the method was called on, so this.balance means "the balance property of this very object". Using this instead of repeating the object name keeps the code working even if the variable is later renamed. You will study this in more depth later in the course; for now, simply read it as "this object".
12. Arrays of Objects: The Shape of Real Data
The single most useful structure in practical JavaScript — and the shape of nearly every list of data you will handle in React — is an array whose elements are objects. Each object describes one item; the array holds the items in order.
let products = [
{ name: "Keyboard", price: 1500 },
{ name: "Mouse", price: 700 },
{ name: "Monitor", price: 8500 }
];
// Read one field of one element
console.log(products[1].name); // "Mouse"
// Loop over the array and use two fields of each object
let total = 0;
for (let item of products) {
console.log(item.name + " costs " + item.price);
total = total + item.price;
}
console.log("Total: " + total);
// Keyboard costs 1500
// Mouse costs 700
// Monitor costs 8500
// Total: 10700
Read an access path from the outside in: products is the array, [1] picks the second object inside it, and .name picks a property of that object. The same outside-in logic works no matter how deeply the data is nested, which is exactly how you will navigate API responses later.
Objects holding arrays
The mirror-image structure is just as common — an object whose property holds an array:
let course = {
title: "React JS Training",
modules: ["JavaScript Fundamentals", "Modern JavaScript", "DOM & Browser APIs"]
};
console.log(course.modules[0]); // "JavaScript Fundamentals"
Between these two patterns — arrays of objects and objects with arrays — you can express almost any real-world data: a course with modules, a cart with products, a user with a list of orders.
13. Arrays vs Objects: Which One When?
Beginners often wonder which structure a given problem needs. This side-by-side comparison settles most cases:
| Question | Array | Object |
| How is data reached? | By index number: list[0] | By key name: item.price |
| Is order meaningful? | Yes — order is the whole point | Not really — keys, not positions, matter |
| How do you count contents? | list.length | Object.keys(obj).length |
| Typical use | A list of similar items: marks, names, products | One entity with named details: a student, a settings panel |
| Best for looping | for...of and forEach | Looping over the keys from Object.keys() |
Rules of thumb
- Many things of the same kind, where order matters → an array.
- One thing with many named details → an object.
- Real data combines both: an array of objects is the normal shape of lists that come from a server.
- Nesting is unlimited: an object can hold arrays, arrays can hold objects, and those can hold more of the same.
Listing an object's keys
let student = { name: "Aisha", age: 21, course: "React JS" };
console.log(Object.keys(student)); // ["name", "age", "course"]
Object.keys() hands you an object's keys as an array — which means everything you learned about arrays on this page can now be applied to objects too. That bridge between the two structures is exactly how real code moves, and it is the foundation the next parts of this module build on.
14. Advanced and Real-World Usage
Searching an array of objects
In real applications you rarely search raw values; you search objects by one of their fields. The pattern is to loop over the array, test each object's property, and keep the matches:
let students = [
{ name: "Aisha", course: "React JS", marks: 88 },
{ name: "Ravi", course: "Python", marks: 75 },
{ name: "Meera", course: "React JS", marks: 92 }
];
// Find the first React JS student
let firstReact = null;
for (let s of students) {
if (s.course === "React JS") {
firstReact = s;
break;
}
}
console.log(firstReact.name); // "Aisha"
// Collect ALL React JS students into a new array
let reactStudents = [];
for (let s of students) {
if (s.course === "React JS") {
reactStudents.push(s);
}
}
console.log(reactStudents.length); // 2
Notice the two shapes of the answer: a single object when you want the first match (start from null so you can detect "not found"), and a new array when you want every match. Both patterns appear constantly in data-handling code and later inside React components that filter a list before rendering it.
Building a summary from an array
Another everyday task is turning a list into a single summary value — a total, an average, a count:
let orders = [
{ item: "Keyboard", amount: 1500 },
{ item: "Mouse", amount: 700 },
{ item: "Cable", amount: 300 }
];
let total = 0;
for (let o of orders) {
total = total + o.amount;
}
console.log("Order value: " + total); // "Order value: 2500"
This "start from a neutral value, add as you loop" technique is called accumulating, and it is the manual version of the reduce concept you will meet in the Modern JavaScript module.
Using objects as lookup tables
A clever and very common use of objects is as a lookup table: instead of a long chain of if conditions, map each possible key to its answer once, then read the answer by key:
let gradePoints = {
A: 10,
B: 8,
C: 6,
D: 4
};
let grade = "B";
console.log(gradePoints[grade]); // 8
Adding a new grade means adding one line to the object, not another branch of conditions. This mapping style scales far better and is a favourite of experienced developers.
Copying safely: reference vs value
Arrays and objects are stored as references. Assigning one to another variable does not copy the contents — both names point at the same data in memory:
let original = [1, 2, 3];
let copy = original; // NOT a real copy — same array!
copy.push(4);
console.log(original); // [1, 2, 3, 4] — original changed too
To make an independent copy, create a new array or object first:
let original = [1, 2, 3];
let realCopy = original.slice(); // a genuine new array
realCopy.push(4);
console.log(original); // [1, 2, 3] — untouched
console.log(realCopy); // [1, 2, 3, 4]
For objects, the simplest beginner-safe copy is to rebuild it property by property, or use Object.assign({}, source), which copies the source's properties into the new empty object:
let user = { name: "Aisha", age: 21 };
let clone = Object.assign({}, user);
clone.age = 22;
console.log(user.age); // 21 — the original is safe
Keep in mind these are shallow copies: nested arrays and objects inside are still shared. The spread operator, which handles this more elegantly, is coming in the Modern JavaScript module.
15. Common Mistakes and the Correct Way
Mistake: counting from 1
let fruits = ["mango", "banana", "papaya"];
console.log(fruits[1]); // "banana" — beginner expected "mango"
Correct way: indexes start at 0. The first element is always fruits[0]. Say it out loud until it is automatic, because every future bug of this kind wastes real debugging time.
Mistake: off-by-one in a loop
for (let i = 0; i <= fruits.length; i++) { // wrong: reads a missing element
console.log(fruits[i]);
}
Correct way: use strict less-than against the length:
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Mistake: comma errors in object literals
// Wrong: comma after the last pair inside the braces is fine,
// but a MISSING comma between pairs is a syntax error
let user = {
name: "Ravi"
age: 22 // SyntaxError: missing comma
};
Correct way: separate every key: value pair with a comma:
let user = {
name: "Ravi",
age: 22
};
Mistake: using dot notation with a variable key
let field = "age";
console.log(user.field); // undefined — looks for a key literally named "field"
Correct way: put the variable inside brackets:
console.log(user[field]); // 22
Mistake: comparing arrays or objects with ===
let a = [1, 2, 3];
let b = [1, 2, 3];
console.log(a === b); // false — different references, even with equal contents
Correct way: compare contents element by element, or compare a simple summary such as the joined string:
console.log(a.join(",") === b.join(",")); // true
This trap matters enormously later: in React, comparing or copying state by reference is behind a large share of beginner bugs, so understanding references now pays off directly.
Mistake: assuming push returns the array
let list = [];
let result = list.push("x"); // push returns the new LENGTH, not the array
console.log(result); // 1
Correct way: push first, then use the array:
list.push("x");
console.log(list); // ["x"]
16. Best Practices
- Prefer array literals and object literals. Square brackets and curly braces are clearer and safer than
new Array() or new Object().
- Use
const for arrays and objects you will not reassign. The contents can still change — const only locks the name to the same reference. The let/const rules are covered fully in the Modern JavaScript module, but adopting const for collections is a good habit from day one.
- Name collections as plurals (
students, products) and single objects as singulars (student, product). Reading students[0].name then explains itself.
- Keep keys consistent. If one object uses
price, do not let another use cost for the same idea; consistent keys make loops and searches predictable.
- Copy before mutating shared data. When an array or object might be used elsewhere, work on a copy made with
slice() or Object.assign() rather than editing the original.
- Build access paths from the outside in. For nested data, write the outermost name, then add one level at a time, checking with
console.log at each step.
- Guard against missing data. Remember that a wrong index or a missing key quietly returns
undefined; check for it before using the value in calculations.
- Keep components of data small and single-purpose — the same principle the React best-practice guides apply to components applies to your data structures: one object should describe one thing clearly.
17. Practical Project: A Student Marks Manager
This project uses everything from both parts of the page: an array of objects, loops, methods, searching, accumulating and a lookup table. You can run it in any browser console or online JavaScript playground.
Step 1: Model the data
Decide the shape first: one array called students, where each object has name, marks (an array of three test scores) and a grade letter to be filled in later.
let students = [
{ name: "Aisha", marks: [78, 92, 85], grade: "" },
{ name: "Ravi", marks: [60, 55, 70], grade: "" },
{ name: "Meera", marks: [95, 88, 91], grade: "" }
];
Step 2: Write a helper to average one student's marks
function average(marksArray) {
let total = 0;
for (let m of marksArray) {
total = total + m;
}
return total / marksArray.length;
}
console.log(average(students[0].marks)); // 85
Step 3: Add a grade lookup table
function gradeFor(avg) {
if (avg >= 90) return "A";
if (avg >= 75) return "B";
if (avg >= 60) return "C";
return "D";
}
Step 4: Process every student
for (let s of students) {
let avg = average(s.marks);
s.grade = gradeFor(avg);
console.log(s.name + " — average " + avg + " — grade " + s.grade);
}
Output:
Aisha — average 85 — grade B
Ravi — average 61.666666666666664 — grade C
Meera — average 91.33333333333333 — grade A
Step 5: Search and summarise
// Find one student by name
function findStudent(name) {
for (let s of students) {
if (s.name === name) {
return s;
}
}
return null;
}
let found = findStudent("Meera");
console.log(found ? found.grade : "Not found"); // "A"
// Count how many achieved grade A or B
let highPerformers = 0;
for (let s of students) {
if (s.grade === "A" || s.grade === "B") {
highPerformers = highPerformers + 1;
}
}
console.log("High performers: " + highPerformers); // 2
Step 6: Extend it yourself
- Add a
push-based function to enrol a new student from three arguments.
- Add a function that returns an array of all students with grade D, using the "collect matches" pattern.
- Round the averages with
Math.round() so the output reads cleanly.
18. Practice Exercises
- Create an array of five city names. Print the first, the last (using
length - 1), and the total number of cities.
- Start with an empty array. Push three numbers, unshift one more, then pop once. Predict the final array on paper before running the code.
- Given
[10, 20, 30, 40], use splice to insert 25 between 20 and 30, then use slice to copy the middle two elements into a new array.
- Create an object describing a laptop with keys
brand, price and ram. Update the price, add a warranty key, and delete ram.
- Write an object with a
greet method that returns "Hello, I am " plus the object's name property, using this.
- Build an array of three book objects, each with
title and price. Loop and print each title, then calculate the total price of all books.
- Write a function that takes an array of numbers and returns a new array containing only the even numbers, using the collect-matches pattern.
- Create a lookup object mapping three Indian city names to their states, then write a function that returns
"Unknown" for any city not in the table.
- Given an array of objects with
name and marks, write a function returning the object with the highest marks (start from the first element and compare as you loop).
- Demonstrate the reference trap: assign one array to a second variable, modify the second, and print both to prove they changed together. Then fix it with
slice().
19. Interview Questions and Answers
What is the difference between an array and an object in JavaScript?
An array is an ordered list of values reached by numeric index starting at 0, best for many similar items where order matters. An object is a collection of key-value pairs reached by key name, best for one entity with named details. Arrays also carry an automatic length property and an ordered set of built-in methods, while objects are unordered mappings from keys to values.
What does array indexes starting at 0 mean in practice?
The first element is at index 0, the second at index 1, and the last is always at length - 1. An array of 3 elements has indexes 0, 1 and 2. Reading an index equal to or beyond length returns undefined rather than an error.
What is the difference between push and unshift?
push adds an element at the end of the array; unshift adds it at the start. Both return the new length of the array. Their removal counterparts are pop (removes from the end) and shift (removes from the start), both returning the removed element.
What is the difference between slice and splice?
slice(start, end) copies a portion into a new array and leaves the original untouched. splice(start, deleteCount, items...) changes the original array by removing and/or inserting elements at a position. The similar names are a classic trap: slice copies, splice cuts.
How do you check whether a value exists in an array?
Use includes(value) for a true/false answer, or indexOf(value), which returns the first matching index or -1 when the value is absent. For arrays of objects, loop and compare the property you care about, since these methods compare whole values, not fields inside objects.
How do you loop through an array, and when would you choose each way?
Use a counted for loop when you need the index as well as the value; use for...of when you only need each element; use forEach when you prefer a method that runs a function per element. All three visit every element in order.
What is the difference between dot notation and bracket notation for objects?
Dot notation (obj.key) works when the key is a simple word known while writing the code. Bracket notation (obj["key"]) is required when the key has spaces or unusual characters, or when the key is stored in a variable — inside brackets you pass the variable without quotes, and JavaScript uses its value as the key.
What does the in operator do for objects?
"key" in obj returns true if the object has that key, and false otherwise. It is the reliable way to test for a key's existence, because simply reading a missing key gives undefined, which cannot distinguish an absent key from a key whose value genuinely is undefined.
What is a method in an object, and what does this mean inside it?
A method is a property whose value is a function, giving the object its own behaviour alongside its data. Inside a method called on an object, this refers to that object, so this.balance reads the balance property of the very object the method was called on.
Why does assigning an array to a new variable not copy it?
Arrays and objects are stored and passed by reference: the variable holds a reference to the data in memory, not the data itself. Assignment copies the reference, so both variables point at the same array and changes through one are visible through the other. A true copy needs slice(), Object.assign() or a similar copying technique.
Why is an array of objects such an important structure?
It is the standard shape of real-world list data: each object describes one item with named fields, and the array holds the items in order. Server responses and JSON data almost always arrive in this shape, and React components typically receive such arrays and render one piece of UI per object, so fluency here directly prepares you for the React modules.
How would you find the student with the highest marks in an array of objects?
Start by assuming the first element is the best, then loop over the rest and replace your "best so far" whenever the current element's marks are higher. This single-pass comparison works for any "find the maximum" question and returns the whole object, not just the number.
20. Quick Revision Checklist
- I can create an array literal and an object literal, and I know why literals are preferred.
- I know indexes start at 0 and the last index is
length - 1.
- I can read, update and add elements by index, and I know out-of-range reads give
undefined.
- I can explain push, pop, shift, unshift and splice, including what each returns.
- I can use includes, indexOf, join, slice and concat, and I never confuse slice with splice.
- I can loop with a counted
for, with for...of and with forEach, and I know when each fits.
- I can read and write object properties with both dot and bracket notation, and I know when brackets are required.
- I can add, update and delete properties, and test for a key with
in.
- I can write an object method and explain what
this refers to inside it.
- I can navigate an array of objects from the outside in and loop over it to search, filter and accumulate.
- I understand reference vs copy for arrays and objects, and how to make a safe copy.
- I can spot the classic mistakes: off-by-one loops, missing commas, variable keys with dots, and comparing arrays with
===.
21. Official Documentation and Further Reading
Conclusion
Arrays and objects are the two containers that hold almost every piece of data a JavaScript program ever touches. An array gives you an ordered list reached by index; an object gives you one thing described by named keys; and the array of objects — the shape of nearly all real data — combines them into the structure you will meet on every screen of this course. You can now create and modify both, add and remove elements with the core methods, loop in three ways, search and summarise collections, and avoid the classic index, comma, notation and reference traps. With these containers under your fingers, the Modern JavaScript module can sharpen them with destructuring, spread and the other ES6+ tools that make working with arrays and objects faster and cleaner.
Learn more in the React JS Training course, or register for a course demo.