Warming up the neural circuits...
Share
Handbook Deep dive Quick Recall Quick recall What you'll learn 6 On this page 21 Arrays & Objects: The Data of Your App
Arrays (ordered lists) and objects (key-value stores) are how you structure data in JavaScript . Almost every app you build will spend most of its time creating, reading, updating, and deleting (CRUD ) data in arrays and objects.
Arrays: Ordered Collections
// Creating arrays
const fruits = [ " apple " , " banana " , " orange " ] ;
const numbers = [ 1 , 2 , 3 , 4 , 5 ] ;
const mixed = [ " hello " , 42 , true , null , { name : " Alice " } ] ;
const empty = [] ;
const size = new Array ( 5 ) ; // [empty × 5]
// Accessing elements
console . log ( fruits [ 0 ]) ; // "apple" (0-indexed)
console . log ( fruits [ 2 ]) ; // "orange"
console . log ( fruits [ - 1 ]) ; // undefined (not like Python!)
console . log ( fruits . length ) ; // 3
Adding & Removing Elements
const items = [] ;
// End
items . push ( " last " ) ; // Add to end: ["last"]
items . pop () ; // Remove from end: []
// Beginning
items . unshift ( "
Finding Elements
const users = [
{ id : 1 , name : " Alice " },
{ id : 2 , name : " Bob " },
{ id : 3 , name : " Charlie " },
] ;
// Find first match
The Big Three: map, filter, reduce
These are the most important array methods you'll use every day.
const numbers = [ 1 , 2 , 3 , 4 , 5 ] ;
const doubled = numbers . map ( n => n * 2 ) ;
console . log ( doubled ) ; // [2, 4, 6, 8, 10]
filter() — Keep Matching Elements
const numbers = [ 1 , 2 , 3 , 4 , 5 , 6 ] ;
const evens = numbers . filter ( n => n % 2 === 0 ) ;
console . log ( evens )
reduce() — Reduce to a Single Value
const numbers = [ 1 , 2 , 3 , 4 , 5 ] ;
// Sum: 15
const sum = numbers . reduce ( ( total , n ) => total + n , 0 ) ;
Objects: Key-Value Stores
// Creating objects
const person = {
name : " Alice " ,
age : 25 ,
isStudent : false ,
address : {
city : " Delhi " ,
country : " India "
},
greet () {
return
Iterating Objects
const user = { name : " Alice " , age : 25 , city : " Delhi " };
// Keys
console . log ( Object . keys ( user )) ; // ["name", "age", "city"]
//
Destructuring
Extract values from arrays and objects into individual variables.
Array Destructuring
const colors = [ " red " , " green " , " blue " ] ;
const [ first , second , third ] = colors ;
console . log ( first ) ; // "red"
Object Destructuring
const user = { name : " Alice " , age : 25 , city : " Delhi " };
const { name , age } = user ;
console . log ( name ) ; // "Alice"
Spread Operator (... )
Array Spread
const arr1 = [ 1 , 2 , 3 ] ;
const arr2 = [ 4 , 5 , 6 ] ;
// Combine arrays
const combined = [ ... arr1 , ... arr2 ] ;
console .
Object Spread
const defaults = { theme : " light " , lang : " en " , fontSize : 14 };
const userPrefs = { theme : " dark " };
// Merge (later overrides earlier)
const settings = { ... defaults
Sorting
const numbers = [ 3 , 1 , 4 , 1 , 5 , 9 ] ;
// Default sort (converts to strings — beware!)
numbers . sort () ; // [1, 1, 3, 4, 5, 9]
// Numeric sort (correct)
numbers . sort ( ( a
JSON (JavaScript Object Notation) is how data travels between servers and browsers.
const user = { name : " Alice " , age : 25 , role : " admin " };
// Convert object to JSON string (serialize)
const jsonString = JSON . stringify ( user ) ;
console . log ( jsonString
Common Mistakes
Mistake 1: Using = to copy arrays/objects (reference copy)
const original = [ 1 , 2 , 3 ] ;
const copy = original ; // ❌ Copying the reference!
copy . push ( 4 ) ; // Mutates original too!
console . log ( original ) ; //
Mistake 2: Forgetting that sort() mutates the original
const numbers = [ 3 , 1 , 4 ] ;
const sorted = numbers . sort () ; // ❌ numbers is also sorted now!
// ✅ Copy first
const sorted = [ ... numbers ] . sort () ;
Mistake 3: Using const with objects thinking they're immutable
const user = { name : " Alice " };
user . name = " Bob " ; // ✅ OK — const prevents reassignment, not mutation
What You've Learned
✅ Array CRUD: push, pop, shift, unshift, splice
✅ Finding: find, findIndex, filter, some, every
✅ Transforming: map, filter, reduce
✅ Objects: create, access, modify, iterate
✅ Destructuring: arrays and objects
✅ Spread: combine, copy, immutable updates
✅ Sort, JSON, common pitfalls
What's Next?
Chapter 12: Async JavaScript — promises, fetch, async /await
Chapter 13: DOM Manipulation — selecting and modifying page elements
Chapter 14: Error Handling — try/catch, custom errors
first
"
)
;
//
Add to start: ["first"]
items . shift () ; // Remove from start: []
// Anywhere
items . splice ( 1 , 0 , " new " ) ; // Insert at index 1
items . splice ( 1 , 1 ) ; // Remove 1 element at index 1
const user = users . find ( u => u . id === 2 ) ;
console . log ( user ) ; // { id: 2, name: "Bob" }
// Find index
const index = users . findIndex ( u => u . name === " Charlie " ) ;
console . log ( index ) ; // 2
// Check if exists
const hasAlice = users . some ( u => u . name === " Alice " ) ; // true
const allAdults = users . every ( u => u . age > 18 ) ; // false
// Filter all matches
const filtered = users . filter ( u => u . id > 1 ) ;
// [{ id: 2, name: "Bob" }, { id: 3, name: "Charlie" }]
// Common pattern: extract a property
const users = [
{ id : 1 , name : " Alice " },
{ id : 2 , name : " Bob " },
] ;
const names = users . map ( user => user . name ) ;
console . log ( names ) ; // ["Alice", "Bob"]
;
//
[2, 4, 6]
const adults = users . filter ( user => user . age >= 18 ) ;
// Max: 5
const max = numbers . reduce ( ( max , n ) => n > max ? n : max , 0 ) ;
// Group by a property
const users = [
{ name : " Alice " , role : " admin " },
{ name : " Bob " , role : " user " },
{ name : " Charlie " , role : " user " },
] ;
const grouped = users . reduce ( ( acc , user ) => {
( acc [ user . role ] = acc [ user . role ] || []) . push ( user ) ;
return acc ;
}, {} ) ;
// { admin: [{ name: "Alice", ... }], user: [{ name: "Bob", ... }, { name: "Charlie", ... }] }
`Hi, I'm
${
this
.
name
}
`
;
}
};
// Accessing properties
console . log ( person . name ) ; // "Alice" (dot notation)
console . log ( person [ " age " ]) ; // 25 (bracket notation — for dynamic keys)
const key = " name " ;
console . log ( person [ key ]) ; // "Alice"
// Adding / modifying
person . email = " alice@example.com " ; // Add new property
person . age = 26 ; // Modify existing
// Deleting
delete person . isStudent ;
// Check if property exists
console . log ( " name " in person ) ; // true
console . log ( person . phone !== undefined ) ; // false
Values
console . log ( Object . values ( user )) ; // ["Alice", 25, "Delhi"]
// Entries (key-value pairs)
console . log ( Object . entries ( user )) ;
// [["name", "Alice"], ["age", 25], ["city", "Delhi"]]
// Loop through keys
for ( const key of Object . keys ( user )) {
console . log ( ` ${ key } : ${ user [ key ] } ` ) ;
}
// for...in loop
for ( const key in user ) {
console . log ( key , user [ key ]) ;
}
console . log ( second ) ; // "green"
// Skip elements
const [ primary , , tertiary ] = colors ;
console . log ( primary ) ; // "red"
console . log ( tertiary ) ; // "blue"
// Rest pattern
const [ head , ... tail ] = [ 1 , 2 , 3 , 4 ] ;
console . log ( head ) ; // 1
console . log ( tail ) ; // [2, 3, 4]
// Default values
const [ a = 0 , b = 0 ] = [ 5 ] ;
console . log ( a ) ; // 5
console . log ( b ) ; // 0 (default)
console . log ( age ) ; // 25
// Rename variables
const { name : fullName , city : location } = user ;
console . log ( fullName ) ; // "Alice"
// Default values
const { name , phone = " N/A " } = user ;
console . log ( phone ) ; // "N/A"
// Nested destructuring
const person = {
name : " Alice " ,
address : { city : " Delhi " , country : " India " }
};
const { address : { city } } = person ;
console . log ( city ) ; // "Delhi"
// Function parameter destructuring
function printUser ({ name , age }) {
console . log ( ` ${ name } is ${ age } years old` ) ;
}
printUser ( user ) ; // "Alice is 25 years old"
log
(
combined
)
;
//
[1, 2, 3, 4, 5, 6]
// Copy array (shallow)
const copy = [ ... arr1 ] ;
// Add elements
const withStart = [ 0 , ... arr1 ] ; // [0, 1, 2, 3]
const withEnd = [ ... arr1 , 4 ] ; // [1, 2, 3, 4]
,
...
userPrefs
};
console . log ( settings ) ;
// { theme: "dark", lang: "en", fontSize: 14 }
// Copy object
const copy = { ... defaults };
// Add properties immutably
const updated = { ... user , role : " admin " };
,
b
)
=>
a
-
b
)
;
//
Ascending: [1, 1, 3, 4, 5, 9]
numbers . sort ( ( a , b ) => b - a ) ; // Descending: [9, 5, 4, 3, 1, 1]
// Sort objects
const users = [
{ name : " Charlie " , age : 30 },
{ name : " Alice " , age : 25 },
{ name : " Bob " , age : 35 },
] ;
users . sort ( ( a , b ) => a . age - b . age ) ; // Sort by age ascending
users . sort ( ( a , b ) => a . name . localeCompare ( b . name )) ; // Sort by name alphabetically
)
;
// '{"name":"Alice","age":25,"role":"admin"}'
// Convert JSON string back to object (parse)
const parsedUser = JSON . parse ( jsonString ) ;
console . log ( parsedUser . name ) ; // "Alice"
// Pretty print
console . log ( JSON . stringify ( user , null , 2 )) ;
// {
// "name": "Alice",
// "age": 25,
// "role": "admin"
// }
[1, 2, 3, 4] — oops!
// ✅ Use spread instead
const realCopy = [ ... original ] ;