0% found this document useful (0 votes)
1 views76 pages

JS Chapter5 Types MasterGuide

This document is a comprehensive guide on JavaScript arrays, covering their definition, creation methods, and various operations such as adding, removing, and modifying elements. It emphasizes the importance of using array literals over the 'new Array()' method and provides detailed explanations of essential array methods like push, pop, splice, and slice. The guide includes analogies, examples, and exercises to reinforce understanding of array concepts.

Uploaded by

Swift Nathan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views76 pages

JS Chapter5 Types MasterGuide

This document is a comprehensive guide on JavaScript arrays, covering their definition, creation methods, and various operations such as adding, removing, and modifying elements. It emphasizes the importance of using array literals over the 'new Array()' method and provides detailed explanations of essential array methods like push, pop, splice, and slice. The guide includes analogies, examples, and exercises to reinforce understanding of array concepts.

Uploaded by

Swift Nathan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Arrays · Multidimensional Arrays · Strings · for...

in · Numbers · Symbols

This guide is a complete rewrite of your Chapter 5 lecture notes — every topic explained from the ground
up, with analogies, detailed syntax breakdowns, extra examples, and the gotchas your notes do not warn
you about. Every lecture has multiple exercises with fully explained solutions. Read it with your browser
console open.

Lecture 1 · JavaScript Arrays — The


Complete Guide
An array is one of the most important data structures in programming. Until now, every variable you
created stored ONE value. An array lets one variable store MANY values — in a specific order, accessible
by position. This changes what you can build entirely.

What Is an Array? Building the Mental Model


An array is an ordered list of values stored under a single variable name. Each value in the list is
called an element. Each element has a position number called its index. Indexes always start at 0.

■ Picture a train with numbered carriages. The whole train is the array — one thing with one name. Each
carriage is an element — it holds one value. The carriage numbers are the indexes — they start at 0, not
1. You access any carriage by saying 'give me carriage number 2'. The train can be as long as you need.

Why Arrays Exist — A Before/After

// WITHOUT arrays — storing 5 student names requires 5 separate variables

let student1 = 'Amara';

let student2 = 'Leo';

let student3 = 'Sara';

let student4 = 'Jack';


let student5 = 'Peter';

// Now imagine 100 students. Or 10,000. Impossible to manage.

// And you cannot loop over them, sort them, or search them easily.

// WITH an array — all 5 names in one structure

let students = ['Amara', 'Leo', 'Sara', 'Jack', 'Peter'];

[Link]([Link]); // 5 — how many students

[Link](students[0]); // Amara — first student

[Link](students[4]); // Peter — last student

// And you can loop, sort, search, filter — all in a few lines.

Creating Arrays
Method 1: Array Literal — Always Use This
Square brackets [ ] with comma-separated values. This is the standard, modern, recommended way.

// Empty array — no elements yet

const emptyList = [];

// Array of numbers

const scores = [88, 92, 75, 100, 63];

// Array of strings

const weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

// Array of booleans

const answers = [true, false, true, true, false];

// Mixed types — JavaScript allows this (though use sparingly)

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 2


const profile = ['Amara', 21, true, null];

// [name, age, isEnrolled, partnerSchool]

// Array of arrays (multidimensional — covered next lecture)

const matrix = [[1, 2], [3, 4], [5, 6]];

// Array of objects

const students = [

{ name: 'Amara', grade: 'A' },

{ name: 'Leo', grade: 'B' },

];

Method 2: new Array() — Know It, Avoid It

// This works but is NEVER recommended

const arr = new Array('eat', 'sleep', 'code');

[Link](arr); // ['eat', 'sleep', 'code']

// The dangerous trap: new Array(3) does NOT create [3]

// It creates an empty array with LENGTH 3!

const trap = new Array(3);

[Link](trap); // [ <3 empty items> ]

[Link]([Link]); // 3

[Link](trap[0]); // undefined

// Contrast with literal:

const safe = [3];

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 3


[Link](safe); // [3]

[Link]([Link]); // 1

// Always use [] literals. No ambiguity.

■■ WATCH OUT

new Array(3) creates a SPARSE array with 3 empty slots — not an array containing the number 3. This is a
classic gotcha. Avoid new Array() completely and always use the [] literal syntax.

Accessing Array Elements


You access elements using bracket notation with the index number. Indexes are zero-based — the first
element is always at index 0.

const colours = ['red', 'green', 'blue', 'yellow', 'purple'];

// 0 1 2 3 4

[Link](colours[0]); // 'red' — first element

[Link](colours[2]); // 'blue' — third element

[Link](colours[4]); // 'purple' — fifth (last) element

[Link](colours[5]); // undefined — no element at index 5

// Getting the LAST element — works for any length

[Link](colours[[Link] - 1]); // 'purple'

// [Link] = 5, 5-1 = 4, colours[4] = 'purple'

// Accessing with a variable as the index

let i = 2;

[Link](colours[i]); // 'blue'

// Changing the index variable lets you access any element

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 4


i = 0;

[Link](colours[i]); // 'red'

Array Length
The .length property returns how many elements are in the array. It is NOT a method — no parentheses
needed. It is always one more than the last valid index.

const fruits = ['apple', 'banana', 'mango'];

[Link]([Link]); // 3

// Indexes: 0, 1, 2 — last valid index is length-1 = 2

const empty = [];

[Link]([Link]); // 0

// length updates automatically as you add/remove elements

[Link]('orange');

[Link]([Link]); // 4 — updated automatically

// Common pattern: loop through every element

for (let i = 0; i < [Link]; i++) {

[Link](i, fruits[i]);

Adding Elements to an Array


push() — Add to the End
push() appends one or more elements to the end of the array and returns the new length.

let tasks = ['wake up', 'brush teeth'];

[Link](tasks); // ['wake up', 'brush teeth']

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 5


[Link]('eat breakfast');

[Link](tasks); // ['wake up', 'brush teeth', 'eat breakfast']

// push returns the NEW length

let newLength = [Link]('exercise');

[Link](newLength); // 4

[Link](tasks); // ['wake up', 'brush teeth', 'eat breakfast', 'exerci


se']

// push multiple elements at once

[Link]('shower', 'commute');

[Link]([Link]); // 6

unshift() — Add to the Beginning


unshift() inserts one or more elements at position 0 and shifts all existing elements right. Returns new
length.

let queue = ['Sara', 'Jack'];

[Link](queue); // ['Sara', 'Jack']

// Someone joins at the front

[Link]('Amara');

[Link](queue); // ['Amara', 'Sara', 'Jack']

// Multiple at front

[Link]('Leo', 'Peter');

[Link](queue); // ['Leo', 'Peter', 'Amara', 'Sara', 'Jack']

// Performance note: unshift is SLOWER than push on large arrays

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 6


// because every existing element must shift one position right.

// push just adds at the end — no shifting needed.

Direct Index Assignment — And Its Trap

let arr = ['a', 'b', 'c']; // indexes 0, 1, 2

// Add at the next index — works fine

arr[3] = 'd';

[Link](arr); // ['a', 'b', 'c', 'd']

// THE TRAP: skip indexes — creates holes filled with undefined

let arr2 = ['x', 'y']; // indexes 0, 1

arr2[5] = 'z'; // jumped from index 1 to index 5

[Link](arr2); // ['x', 'y', undefined, undefined, undefined, 'z']

[Link]([Link]); // 6

[Link](arr2[2]); // undefined

// Never jump indexes deliberately. Use push() to add safely.

■■ WATCH OUT

Assigning to an index beyond the current array length does not throw an error — it silently creates a sparse
array with undefined holes. These holes cause subtle bugs in loops and calculations. Always use push() to
add elements safely.

Removing Elements from an Array


pop() — Remove from the End
pop() removes the last element and returns it. This is important — you can capture what was removed.

let stack = ['first', 'second', 'third'];

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 7


// Remove last — discard the removed value

[Link]();

[Link](stack); // ['first', 'second']

// Remove last — KEEP the removed value

let removed = [Link]();

[Link](removed); // 'second'

[Link](stack); // ['first']

// pop() on empty array returns undefined

[Link](); // removes 'first'

let nothing = [Link]();

[Link](nothing); // undefined — nothing to remove

shift() — Remove from the Beginning


shift() removes the first element, shifts all other elements left by one position, and returns the removed
element.

let queue = ['first in line', 'second', 'third'];

// Process the first person in the queue

let served = [Link]();

[Link]('Serving:', served); // Serving: first in line

[Link]('Queue now:', queue); // Queue now: ['second', 'third']

// Performance: like unshift, shift is slow on large arrays

// because every remaining element must shift left.

Modifying Existing Elements

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 8


let grades = [85, 90, 78, 92];

// Change element at index 2

grades[2] = 95;

[Link](grades); // [85, 90, 95, 92]

// Apply a transformation

grades[0] = grades[0] + 5; // add bonus points to first grade

[Link](grades); // [90, 90, 95, 92]

// or using +=

grades[1] += 5;

[Link](grades); // [90, 95, 95, 92]

Essential Array Methods — Deep Dive


splice() — The Swiss Army Knife
splice(start, deleteCount, ...itemsToInsert) is the most powerful array modifier. It can
remove elements, insert elements, or both — at any position. It modifies the original array and returns an
array of the removed elements.

let fruits = ['apple', 'banana', 'mango', 'orange', 'grape'];

// ■■ REMOVE elements ■■

// splice(startIndex, numberOfToDelete)

let removed = [Link](1, 2); // start at index 1, remove 2

[Link](removed); // ['banana', 'mango'] — what was removed

[Link](fruits); // ['apple', 'orange', 'grape'] — what remains

// ■■ INSERT elements (without removing) ■■

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 9


// splice(insertAtIndex, 0, ...newItems) — 0 means delete nothing

[Link](1, 0, 'kiwi', 'lemon');

[Link](fruits); // ['apple', 'kiwi', 'lemon', 'orange', 'grape']

// ■■ REPLACE elements (remove then insert) ■■

// splice(startIndex, deleteCount, ...replacements)

[Link](2, 1, 'pineapple'); // remove 1 at index 2, insert 'pineapple'

[Link](fruits); // ['apple', 'kiwi', 'pineapple', 'orange', 'grape']

// ■■ Remove from the end using negative index ■■

[Link](-1, 1); // -1 means 'last element'

[Link](fruits); // ['apple', 'kiwi', 'pineapple', 'orange']

slice() — Extract Without Modifying


slice(start, end) returns a NEW array containing elements from start up to (but NOT including) end.
The original array is untouched.

const letters = ['a', 'b', 'c', 'd', 'e', 'f'];

// 0 1 2 3 4 5

// slice(start, end) — end is EXCLUSIVE

[Link]([Link](1, 4)); // ['b', 'c', 'd'] (indexes 1,2,3 — NOT 4)

[Link]([Link](2)); // ['c', 'd', 'e', 'f'] (to the end)

[Link]([Link](0, 3)); // ['a', 'b', 'c']

// Negative indexes — count from the end

[Link]([Link](-2)); // ['e', 'f'] (last 2 elements)

[Link]([Link](-4, -1)); // ['c', 'd', 'e']

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 10


// Original is NOT modified

[Link](letters); // ['a', 'b', 'c', 'd', 'e', 'f'] — unchanged

// slice() with no args = shallow copy of the whole array

const copy = [Link]();

[Link](copy); // ['a', 'b', 'c', 'd', 'e', 'f']

indexOf() — Finding Elements

const animals = ['cat', 'dog', 'bird', 'dog', 'fish'];

// indexOf returns the FIRST matching index, or -1 if not found

[Link]([Link]('dog')); // 1 — first 'dog' is at index 1

[Link]([Link]('fish')); // 4

[Link]([Link]('lion')); // -1 — not in array

// Search starting from a position

[Link]([Link]('dog', 2)); // 3 — finds the SECOND 'dog'

// Use -1 check to verify existence

if ([Link]('bird') !== -1) {

[Link]('Bird is in the list');

// includes() is often cleaner for existence checks:

[Link]([Link]('cat')); // true

[Link]([Link]('lion')); // false

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 11


concat() — Joining Arrays

const team1 = ['Amara', 'Leo'];

const team2 = ['Sara', 'Jack'];

const team3 = ['Peter'];

// concat returns a NEW combined array — originals unchanged

const allStudents = [Link](team2);

[Link](allStudents); // ['Amara', 'Leo', 'Sara', 'Jack']

// concat multiple arrays at once

const everyone = [Link](team2, team3);

[Link](everyone); // ['Amara', 'Leo', 'Sara', 'Jack', 'Peter']

// Modern alternative: spread operator (ES6)

const merged = [...team1, ...team2, ...team3];

[Link](merged); // ['Amara', 'Leo', 'Sara', 'Jack', 'Peter']

sort() — Sorting Arrays


sort() sorts the array in place (modifies original). By default, it converts everything to strings and sorts
alphabetically — which produces wrong results for numbers. Understanding this quirk is essential.

// Sorting strings — works as expected

let fruits = ['mango', 'apple', 'banana', 'kiwi'];

[Link]();

[Link](fruits); // ['apple', 'banana', 'kiwi', 'mango']

// Sorting numbers — DEFAULT SORT IS WRONG FOR NUMBERS

let nums = [10, 2, 100, 1, 20];

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 12


[Link]();

[Link](nums); // [1, 10, 100, 2, 20] ← WRONG! Alphabetical order

// '10' comes before '2' alphabetically (like 'ab' before 'b')

// CORRECT numeric sort — use a comparator function

[Link]((a, b) => a - b); // ascending

[Link](nums); // [1, 2, 10, 20, 100] ← CORRECT

[Link]((a, b) => b - a); // descending

[Link](nums); // [100, 20, 10, 2, 1]

// How the comparator works:

// If (a - b) is negative → a comes first

// If (a - b) is positive → b comes first

// If (a - b) is 0 → order unchanged

■■ WATCH OUT

sort() with numbers WITHOUT a comparator function produces wrong results — it sorts alphabetically, so
100 comes before 2 because '1' < '2' as strings. Always pass (a, b) => a - b for ascending numeric sort. This
trips up almost every beginner.

forEach() — Iterating Over Every Element


forEach() calls a function once for each element in the array, in order. It does not return a new array —
it is used purely for side effects like printing or updating.

const scores = [88, 72, 95, 63, 80];

// Basic forEach — receives each element

[Link](function(score) {

[Link](score);

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 13


});

// prints: 88, 72, 95, 63, 80

// Arrow function syntax (cleaner — covered in Chapter 7)

[Link](score => [Link](score));

// forEach also gives you the index and the array itself

[Link]((score, index) => {

[Link](`Position ${index}: ${score}`);

});

// Position 0: 88

// Position 1: 72 ... etc

// Real example: add 5 bonus points to every score

let total = 0;

[Link](score => {

total += score;

});

[Link]('Total:', total); // Total: 398

[Link]('Average:', total / [Link]); // Average: 79.6

find() and findIndex()

const products = [

{ name: 'Laptop', price: 800 },

{ name: 'Phone', price: 400 },

{ name: 'Tablet', price: 600 },

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 14


];

// find() returns the FIRST element where the condition is true

let expensive = [Link](p => [Link] > 500);

[Link](expensive); // { name: 'Laptop', price: 800 }

// findIndex() returns the INDEX of the first match, or -1

let idx = [Link](p => [Link] === 'Phone');

[Link](idx); // 1

// No match — returns undefined (find) or -1 (findIndex)

let notFound = [Link](p => [Link] > 1000);

[Link](notFound); // undefined

Arrays Are Objects — The Reference Trap


This is one of the most important things to understand about arrays. In JavaScript, arrays are objects, and
objects are stored by reference, not by value. This means when you assign an array to a new variable,
you are NOT copying the array — both variables point to the same array in memory.

■ Imagine two people holding the same whiteboard between them. If person A writes on it, person B
sees the change — because they are looking at the same physical board. Variables that reference the
same array are like two people holding the same whiteboard.

let original = ['a', 'b', 'c'];

let copy = original; // NOT a copy — both point to the SAME array

[Link]('d'); // modifies the array through 'copy'

[Link](original); // ['a', 'b', 'c', 'd'] — original ALSO changed!

[Link](copy); // ['a', 'b', 'c', 'd']

// To make a TRUE independent copy:

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 15


// Method 1: slice()

let realCopy1 = [Link]();

// Method 2: spread operator (most modern)

let realCopy2 = [...original];

// Method 3: [Link]()

let realCopy3 = [Link](original);

[Link]('e');

[Link](original); // ['a', 'b', 'c', 'd'] — unchanged!

[Link](realCopy1); // ['a', 'b', 'c', 'd', 'e'] — independent

■ DEEP DIVE

This is called 'copy by reference' and it applies to ALL objects in JavaScript, including arrays. It is one of the
most common sources of bugs in real projects. When you pass an array to a function and the function
modifies it, your original array changes too. Always be conscious of whether you need a copy or a reference.

Exercise 1 — Building a Student Gradebook


You are building a gradebook for Rebase Academy. Complete all the following steps in order:

• Create an array called grades containing: 88, 72, 95, 63, 80, 91

• Print the array and its length

• Print the first and last grades using index notation

• A new student joined — add grade 77 to the end

• The first entry was wrong — remove it with shift()

• Sort the grades in descending order (highest first)

• Calculate and print the average of the final array

Solution & Explanation

// Step 1: Create the array

let grades = [88, 72, 95, 63, 80, 91];

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 16


// Step 2: Print and length

[Link]('Grades:', grades);

[Link]('Count:', [Link]); // 6

// Step 3: First and last

[Link]('First:', grades[0]); // 88

[Link]('Last:', grades[[Link] - 1]); // 91

// Step 4: Add new student grade

[Link](77);

[Link]('After push:', grades); // [88, 72, 95, 63, 80, 91, 77]

// Step 5: Remove first (wrong entry)

let removed = [Link]();

[Link]('Removed:', removed); // 88

[Link]('After shift:', grades); // [72, 95, 63, 80, 91, 77]

// Step 6: Sort descending (highest first)

[Link]((a, b) => b - a);

[Link]('Sorted:', grades); // [95, 91, 80, 77, 72, 63]

// Step 7: Calculate average

let total = 0;

[Link](g => total += g);

let average = total / [Link];

[Link]('Average:', [Link](1)); // Average: 79.7

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 17


■■ NOTE

Notice how toFixed(1) formats the average to 1 decimal place for clean display. Without it, floating-point
arithmetic might give you something like 79.66666... toFixed() is essential for presenting numeric results to
users.

Exercise 2 — Array Reference vs Copy


This exercise is about the most common array bug. Predict the output of each [Link] BEFORE
running the code. Then run it and explain any surprises.

let listA = [1, 2, 3];

let listB = listA;

[Link](4);

[Link]('A:', listA);

[Link]('B:', listB);

[Link]('Same?', listA === listB);

// Now fix it — make listC a true independent copy of listA

let listC = ???;

[Link](99);

[Link]('A still:', listA); // should be unchanged

[Link]('C:', listC);

Solution & Explanation

let listA = [1, 2, 3];

let listB = listA; // reference, NOT copy

[Link](4);

[Link]('A:', listA); // [1, 2, 3, 4] — changed! same array.

[Link]('B:', listB); // [1, 2, 3, 4] — same.

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 18


[Link]('Same?', listA === listB); // true — same memory address

// Fix: use spread to create a real copy

let listC = [...listA]; // independent copy

[Link](99);

[Link]('A still:', listA); // [1, 2, 3, 4] — unchanged!

[Link]('C:', listC); // [1, 2, 3, 4, 99]

■ DEEP DIVE

listA === listB is true because === for objects/arrays checks whether both variables point to the SAME
memory location, not whether the contents are equal. Even two arrays with identical contents are not === if
they are different objects: [1,2,3] === [1,2,3] is FALSE. This is copy-by-reference in action.

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 19


Lecture 2 · Multidimensional Arrays
A multidimensional array is an array whose elements are themselves arrays. The most common form is a
2D array — a grid of rows and columns — though you can nest as deeply as needed. They model
real-world data structures like spreadsheets, game boards, and matrices.

■ Think of a spreadsheet: the whole spreadsheet is the outer array. Each row is an inner array. Each cell
is an element inside a row. You navigate to any cell by saying 'row 2, column 3' — which translates to
array[1][2] (zero-based).

Creating 2D Arrays
// Inline — array of arrays

const grid = [

[1, 2, 3], // row 0

[4, 5, 6], // row 1

[7, 8, 9], // row 2

];

// Building from named arrays

let row0 = ['Jack', 24, 'Engineering'];

let row1 = ['Sara', 23, 'Design'];

let row2 = ['Peter', 25, 'Marketing'];

let students = [row0, row1, row2];

// Mixed-length inner arrays are valid

const jagged = [[1], [2, 3], [4, 5, 6, 7]];

Accessing Elements with Double Bracket Notation


Use array[outerIndex][innerIndex]. The first bracket selects a row (inner array). The second
bracket selects a column (element within that row).

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 20


let x = [

['Jack', 24], // row 0: x[0]

['Sara', 23], // row 1: x[1]

['Peter', 24], // row 2: x[2]

];

// Access entire row

[Link](x[0]); // ['Jack', 24]

[Link](x[1]); // ['Sara', 23]

// Access specific cell

[Link](x[0][0]); // 'Jack' — row 0, column 0

[Link](x[0][1]); // 24 — row 0, column 1

[Link](x[1][0]); // 'Sara' — row 1, column 0

[Link](x[2][1]); // 24 — row 2, column 1

// Mental model: x[ROW][COLUMN]

// Row = first index, Column = second index

Adding and Removing in Multidimensional Arrays


Outer Array Operations

let data = [['Jack', 24], ['Sara', 23]];

// Add a new ROW to the end

[Link](['Peter', 25]);

[Link](data);

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 21


// [['Jack', 24], ['Sara', 23], ['Peter', 25]]

// Insert a row at position 1 using splice

[Link](1, 0, ['Leo', 22]);

[Link](data);

// [['Jack', 24], ['Leo', 22], ['Sara', 23], ['Peter', 25]]

// Remove the last row

[Link]();

[Link](data);

// [['Jack', 24], ['Leo', 22], ['Sara', 23]]

// Remove a specific row by index

[Link](1, 1); // remove 1 row starting at index 1

[Link](data);

// [['Jack', 24], ['Sara', 23]]

Inner Array Operations

let students = [['Jack', 24], ['Sara', 23]];

// Add a column to row 1 (Sara's row)

students[1].push('Design'); // Sara's subject

[Link](students);

// [['Jack', 24], ['Sara', 23, 'Design']]

// Or use index assignment

students[0][2] = 'Engineering'; // Jack's subject

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 22


[Link](students);

// [['Jack', 24, 'Engineering'], ['Sara', 23, 'Design']]

// Remove a column from a specific row

students[1].pop(); // remove 'Design' from Sara's row

[Link](students);

// [['Jack', 24, 'Engineering'], ['Sara', 23]]

Iterating Over Multidimensional Arrays


You need nested loops or nested forEach calls — one loop for the outer array, one for each inner array.

Method 1: Traditional for Loop (Most Explicit)

let grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

for (let row = 0; row < [Link]; row++) {

for (let col = 0; col < grid[row].length; col++) {

[Link](`grid[${row}][${col}] = ${grid[row][col]}`);

// grid[0][0] = 1

// grid[0][1] = 2

// grid[0][2] = 3

// grid[1][0] = 4 ... etc

Method 2: forEach (Cleaner)

let students = [['Jack', 24], ['Sara', 23], ['Peter', 25]];

[Link]((student, rowIndex) => {

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 23


[Link]((value, colIndex) => {

[Link](`Row ${rowIndex}, Col ${colIndex}: ${value}`);

});

});

// More practical: print formatted rows

[Link](student => {

[Link](`Name: ${student[0]}, Age: ${student[1]}`);

});

// Name: Jack, Age: 24

// Name: Sara, Age: 23

// Name: Peter, Age: 25

Real-World Example: A Tic-Tac-Toe Board


2D arrays are perfect for grid-based data. Here is a complete example modelling a tic-tac-toe board:

// 3x3 board — empty squares are null

let board = [

['X', 'O', null],

[null, 'X', null],

['O', null, 'X'],

];

// Print the board nicely

function printBoard(b) {

[Link](row => {

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 24


[Link]([Link](cell => cell || '-').join(' | '));

});

[Link]('');

printBoard(board);

// X | O | -

// - | X | -

// O | - | X

// Make a move — place 'O' at row 0, col 2

board[0][2] = 'O';

printBoard(board);

// X | O | O

// - | X | -

// O | - | X

Exercise 3 — Student Gradebook — 2D Array


Build a 2D array representing a class gradebook. Each row is one student: [name, math, english, science].

• Create the array with 4 students and 3 subject grades each

• Print each student's name and their average grade

• Find and print the student with the highest average

Solution & Explanation

let gradebook = [

['Amara', 88, 92, 85],

['Leo', 72, 68, 75],

['Sara', 95, 90, 98],

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 25


['Jack', 60, 74, 55],

];

// Print each student's average

let topStudent = null;

let topAverage = 0;

[Link](student => {

let name = student[0];

// Grades are at indexes 1, 2, 3

let avg = (student[1] + student[2] + student[3]) / 3;

[Link](`${name}: avg = ${[Link](1)}`);

if (avg > topAverage) {

topAverage = avg;

topStudent = name;

});

[Link](`Top student: ${topStudent} (${[Link](1)})`);

OUTPUT :

Amara: avg = 88.3

Leo: avg = 71.7

Sara: avg = 94.3

Jack: avg = 63.0

Top student: Sara (94.3)

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 26


Lecture 3 · JavaScript Strings — Complete
Guide
You have been using strings since Chapter 1. This lecture goes much deeper — covering how strings
work internally, every important method, escape sequences, immutability, and the things that trip up every
intermediate developer.

What Is a String? How It Works Internally


A string is a sequence of characters stored in a specific order. Internally, JavaScript stores each
character as a number using the Unicode standard — every character in every human language has a
unique number (called a code point). When you type 'A', JavaScript stores the number 65. When you type
'a', it stores 97.

This is why strings are case-sensitive — 'A' and 'a' have different Unicode values. And why string
comparison works alphabetically — it compares the Unicode values character by character.

// charCodeAt() shows the Unicode value of a character

[Link]('A'.charCodeAt(0)); // 65

[Link]('a'.charCodeAt(0)); // 97

[Link]('Z'.charCodeAt(0)); // 90

[Link]('0'.charCodeAt(0)); // 48 — the digit zero

// This is why uppercase < lowercase in comparisons:

[Link]('A' < 'a'); // true — 65 < 97

[Link]('Z' < 'a'); // true — 90 < 97

[Link]('apple' < 'banana'); // true — 'a'(97) < 'b'(98)

Strings Are Immutable — A Critical Property


In JavaScript, strings are immutable — once created, you cannot change individual characters. You can
only create new strings. This is completely different from arrays.

let greeting = 'hello';

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 27


// Trying to change a character — silently fails (no error!)

greeting[0] = 'H';

[Link](greeting); // 'hello' — unchanged! The assignment did nothing.

// The ONLY way to 'change' a string is to create a NEW one

greeting = 'Hello'; // reassign the variable to a completely new string

[Link](greeting); // 'Hello'

// All string methods return NEW strings — they never modify the original

const original = 'hello';

const upper = [Link](); // returns NEW string

[Link](original); // 'hello' — still lowercase

[Link](upper); // 'HELLO' — the new string

■■ NOTE

String immutability is a deliberate design decision. It makes strings safe to share between parts of a program
without worrying about unexpected modification. Every string method — toUpperCase, replace, slice, trim —
returns a brand new string. The original is always untouched.

Accessing Characters
const word = 'JavaScript';

// 0123456789

// Method 1: Bracket notation (same as arrays)

[Link](word[0]); // 'J'

[Link](word[4]); // 'S'

[Link](word[9]); // 't'

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 28


[Link](word[10]); // undefined — out of bounds

// Method 2: charAt() — older, slightly different behaviour

[Link]([Link](0)); // 'J'

[Link]([Link](10)); // '' — empty string (not undefined)

// Getting the last character

[Link](word[[Link] - 1]); // 't'

[Link]([Link]([Link] - 1)); // 't'

// at() — new method, supports negative indexes

[Link]([Link](-1)); // 't' — last character

[Link]([Link](-2)); // 'p' — second from last

Escape Characters — Including Special Characters in Strings


Sometimes you need to include characters in a string that would normally confuse the parser — like a
quote inside a quoted string, or a newline. You use a backslash \ followed by a code character to
represent these.

Escape Sequence What It Produces Example

\' Single quote inside 'It\'s great' --> It's great


single-quoted string

\" Double quote inside He said \"hi\" -- inside string


double-quoted string

\\ A literal backslash 'C:\\Users' --> C:\Users

\n Newline — moves to next line 'Line1\nLine2'

\t Tab — horizontal indentation 'Name:\tAmara'

\r Carriage return (used in Rarely needed directly


Windows line endings)

\b Backspace Rarely used in modern code

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 29


\u{XXXX} Unicode character by code '\u{1F600}' --> ■
point

// Apostrophes in single-quoted strings

const msg1 = 'It\'s a beautiful day in Yaoundé.';

[Link](msg1); // It's a beautiful day in Yaoundé.

// Or just switch to double quotes — no escape needed

const msg2 = "It's a beautiful day in Yaoundé.";

[Link](msg2); // It's a beautiful day in Yaoundé.

// Newlines

const poem = 'Roses are red,\nViolets are blue,\nI code in JS,\nAnd so should you.'
;

[Link](poem);

// Roses are red,

// Violets are blue,

// I code in JS,

// And so should you.

// Tabs — useful for formatted output

[Link]('Name:\tAmara');

[Link]('Score:\t95');

// Name: Amara

// Score: 95

// Windows file path — double backslash for literal backslash

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 30


const path = 'C:\\Users\\Amara\\Documents';

[Link](path); // C:\Users\Amara\Documents

// Emoji via Unicode

[Link]('\u{1F600}'); // ■

[Link]('\u{2764}'); // ❤

Essential String Methods — Every One Explained


Length

const text = 'Hello, World!';

[Link]([Link]); // 13

// Counts every character including spaces, commas, exclamation marks

const empty = '';

[Link]([Link]); // 0

// Useful for validation

let password = 'abc';

if ([Link] < 8) {

[Link]('Password too short! Minimum 8 characters.');

toUpperCase() and toLowerCase()

const name = 'amara nkeng';

[Link]([Link]()); // 'AMARA NKENG'

[Link]([Link]()); // 'amara nkeng' (already lower)

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 31


// CRITICAL USE: case-insensitive comparison

let userInput = 'YES';

let expected = 'yes';

// BAD: fails for 'YES', 'Yes', 'yEs' etc

[Link](userInput === expected); // false

// GOOD: normalise both to lowercase before comparing

[Link]([Link]() === [Link]()); // true

// Capitalising first letter (common pattern)

const word = 'javascript';

const capitalised = word[0].toUpperCase() + [Link](1);

[Link](capitalised); // 'Javascript'

trim(), trimStart(), trimEnd()

// trim() removes whitespace from BOTH ends

const messy = ' hello world ';

[Link]([Link]()); // 'hello world'

[Link]([Link]()); // 'hello world ' (left only)

[Link]([Link]()); // ' hello world' (right only)

// Why this matters: user form inputs often have accidental spaces

let emailInput = ' amara@[Link] ';

let cleanEmail = [Link]();

[Link](cleanEmail); // 'amara@[Link]'

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 32


// Always trim user inputs before storing or comparing them

includes(), startsWith(), endsWith()

const sentence = 'JavaScript is a powerful programming language.';

// includes() — does the string contain this substring?

[Link]([Link]('powerful')); // true

[Link]([Link]('Python')); // false

[Link]([Link]('java')); // false — case-sensitive!

// startsWith() — does it begin with this?

[Link]([Link]('JavaScript')); // true

[Link]([Link]('Python')); // false

// endsWith() — does it finish with this?

[Link]([Link]('language.')); // true

[Link]([Link]('language')); // false — missing the dot

// Real use: checking file types

let filename = 'report_2025.pdf';

if ([Link]('.pdf')) {

[Link]('This is a PDF file');

indexOf() and lastIndexOf()

const text = 'banana';

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 33


// indexOf — position of FIRST occurrence, or -1

[Link]([Link]('a')); // 1 — first 'a' is at index 1

[Link]([Link]('an')); // 1 — 'an' starts at index 1

[Link]([Link]('z')); // -1 — not found

// lastIndexOf — position of LAST occurrence

[Link]([Link]('a')); // 5 — last 'a' is at index 5

// Real use: checking file extension

let file = '[Link]';

let lastDot = [Link]('.');

let extension = [Link](lastDot + 1);

[Link](extension); // 'pdf'

slice() — Extract a Substring


slice(start, end) returns a new string from start up to (not including) end. Supports negative
indexes.

const str = 'Hello, World!';

// 0123456789...

[Link]([Link](0, 5)); // 'Hello' — indexes 0,1,2,3,4

[Link]([Link](7)); // 'World!' — from 7 to end

[Link]([Link](7, 12)); // 'World' — indexes 7 to 11

[Link]([Link](-6)); // 'orld!' — last 6 chars

[Link]([Link](-6, -1)); // 'orld' — last 6, not last 1

// Practical: get the domain from an email

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 34


const email = 'amara@[Link]';

const atPos = [Link]('@');

const domain = [Link](atPos + 1);

[Link](domain); // '[Link]'

replace() and replaceAll()

const text = 'I love cats. Cats are amazing. My cat is the best.';

// replace() — replaces ONLY the first match

[Link]([Link]('cat', 'dog'));

// 'I love dogs. Cats are amazing. My cat is the best.'

// Note: 'Cats' was NOT replaced (case-sensitive), and the second 'cat' was not eit
her

// replaceAll() — replaces ALL matches

[Link]([Link]('cat', 'dog'));

// 'I love dogs. Cats are amazing. My dog is the best.'

// Still case-sensitive: 'Cats' unchanged

// Case-insensitive replace using regex (forward slashes, /i flag)

[Link]([Link](/cat/gi, 'dog'));

// 'I love dogs. dogs are amazing. My dog is the best.'

// /cat/gi means: find 'cat', g=all occurrences, i=case-insensitive

split() — String to Array


split(separator) breaks a string into an array of substrings, cutting at every occurrence of the
separator. It is the reverse of join().

// Split by comma

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 35


const csv = 'Amara,Leo,Sara,Jack,Peter';

const names = [Link](',');

[Link](names); // ['Amara', 'Leo', 'Sara', 'Jack', 'Peter']

[Link]([Link]); // 5

// Split by space

const sentence = 'JavaScript is awesome';

const words = [Link](' ');

[Link](words); // ['JavaScript', 'is', 'awesome']

// Split every character — pass empty string ''

const letters = 'hello'.split('');

[Link](letters); // ['h', 'e', 'l', 'l', 'o']

// split then join — powerful string transformation

const kebab = 'hello-world-from-js';

const camel = [Link]('-').map((word, i) =>

i === 0 ? word : word[0].toUpperCase() + [Link](1)

).join('');

[Link](camel); // 'helloWorldFromJs'

repeat() and padStart() / padEnd()

// repeat() — duplicate a string n times

[Link]('ha'.repeat(3)); // 'hahaha'

[Link]('='.repeat(20)); // '===================='

[Link]('-'.repeat(0)); // ''

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 36


// padStart(targetLength, padString) — pad from the LEFT

// Use case: formatting numbers with leading zeros

[Link]('5'.padStart(3, '0')); // '005'

[Link]('42'.padStart(5, '0')); // '00042'

[Link]('hello'.padStart(8)); // ' hello' (default pad is space)

// padEnd(targetLength, padString) — pad from the RIGHT

[Link]('name'.padEnd(10, '.')); // 'name......'

[Link]('42'.padEnd(5, '0')); // '42000'

// Real use: displaying time as 09:05 instead of 9:5

let hours = 9;

let minutes = 5;

let timeStr = String(hours).padStart(2,'0') + ':' + String(minutes).padStart(2,'0')


;

[Link](timeStr); // '09:05'

Template Literals — Advanced Usage


// Multi-line without escape characters

const email = `Dear Amara,

Congratulations! You have passed Chapter 5 with distinction.

Best regards,

Rebase Academy`;

[Link](email);

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 37


// Expressions — any valid JS goes inside ${}

let a = 5, b = 3;

[Link](`${a} + ${b} = ${a + b}`); // 5 + 3 = 8

[Link](`${a} * ${b} = ${a * b}`); // 5 * 3 = 15

[Link](`Max: ${[Link](a, b)}`); // Max: 5

// Conditional inside template literal

let score = 72;

let pass = score >= 50;

[Link](`Score: ${score} — ${pass ? 'PASS' : 'FAIL'}`);

// Score: 72 — PASS

// Nested template literals

let students = ['Amara', 'Leo', 'Sara'];

[Link](`Class has ${[Link]} student${[Link] !== 1 ? 's' : ''


}`);

// Class has 3 students

Exercise 4 — String Processing Challenge


A user has submitted a registration form. Their inputs need cleaning and validation before being saved.
Process the following raw inputs:

let rawName = ' amara nkeng ';

let rawEmail = ' AMARA@[Link] ';

let rawPassword = 'pass';

// Tasks:

// 1. Trim whitespace from all fields

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 38


// 2. Capitalise the name properly (each word capitalised)

// 3. Lowercase the email

// 4. Check password length is at least 8 chars — if not, print error

// 5. Check email contains '@' — if not, print error

// 6. Print a confirmation if all checks pass

Solution & Explanation

let rawName = ' amara nkeng ';

let rawEmail = ' AMARA@[Link] ';

let rawPassword = 'pass';

// Step 1: Trim all fields

let name = [Link]();

let email = [Link]().toLowerCase();

let password = [Link]();

// Step 2: Capitalise each word of the name

let properName = [Link](' ')

.map(word => word[0].toUpperCase() + [Link](1))

.join(' ');

// Step 3 (included in step 1 above)

// Step 4: Validate password length

let isPasswordValid = [Link] >= 8;

if (!isPasswordValid) {

[Link]('Error: Password must be at least 8 characters');

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 39


}

// Step 5: Validate email

let isEmailValid = [Link]('@');

if (!isEmailValid) {

[Link]('Error: Email must contain @');

// Step 6: Confirm if all valid

if (isPasswordValid && isEmailValid) {

[Link]('Registration successful!');

[Link](`Welcome, ${properName}!`);

[Link](`Email: ${email}`);

} else {

[Link]('Registration failed. Please fix the errors above.');

OUTPUT :

Error: Password must be at least 8 characters

Registration failed. Please fix the errors above.

■ DEEP DIVE

This exercise models REAL input sanitisation — one of the most common tasks in web development. Notice
how chaining methods works: [Link](' ').map(...).join(' ') reads as a pipeline: split into words, transform
each word, rejoin. This functional style is idiomatic modern JavaScript.

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 40


Lecture 4 · The for...in Loop
The for...in loop iterates over the property keys of an object. It is one of several loop types in JavaScript,
each designed for a specific purpose. Understanding which loop to use when is a sign of real competence.

Syntax and How It Works


for (let key in object) {

// 'key' holds the current property name (as a string)

// access the value with: object[key]

// ■■ FULL ANATOMY ■■

const student = { name: 'Amara', age: 21, grade: 'A' };

for (let key in student) {

[Link](key); // prints: name, age, grade

[Link](student[key]); // prints: Amara, 21, A

[Link](`${key}: ${student[key]}`);

// name: Amara

// age: 21

// grade: A

Why You Need object[key] and Not [Link]


When you access a property using a variable, you MUST use bracket notation. Dot notation only works
with literal property names. This is a common beginner mistake:

const person = { name: 'Leo', city: 'Yaounde' };

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 41


for (let key in person) {

[Link]([Link]); // undefined — JS looks for a property literally na


med 'key'

[Link](person[key]); // correct — uses the VALUE of the variable 'key'

// Think of it this way:

// [Link] → 'Leo' (dot notation with literal property name)

// let k = 'name';

// person[k] → 'Leo' (bracket notation with variable)

// person.k → undefined (JS looks for property named 'k', not 'name')

Practical Examples
Iterating an Object and Transforming Values

const salaries = {

Amara: 45000,

Leo: 38000,

Sara: 52000,

Jack: 41000,

};

// Print formatted salaries with currency symbol

for (let employee in salaries) {

let formatted = '$' + salaries[employee].toLocaleString();

[Link](`${employee}: ${formatted}`);

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 42


// Amara: $45,000

// Leo: $38,000 etc.

// Calculate total payroll

let totalPayroll = 0;

for (let employee in salaries) {

totalPayroll += salaries[employee];

[Link]('Total payroll: $' + [Link]());

// Total payroll: $176,000

Counting and Filtering Properties

const inventory = {

apples: 50,

bananas: 0,

mangoes: 12,

oranges: 0,

grapes: 30,

};

// Count how many items are in stock

let inStockCount = 0;

let outOfStock = [];

for (let item in inventory) {

if (inventory[item] > 0) {

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 43


inStockCount++;

} else {

[Link](item);

[Link]('In stock:', inStockCount); // In stock: 3

[Link]('Out of stock:', outOfStock); // Out of stock: ['bananas', 'orang


es']

for...in With Strings (and Why to Be Careful)


const word = 'hello';

// for...in iterates INDEXES of the string (as strings: '0', '1', ...)

for (let i in word) {

[Link](i, word[i]);

// '0' h

// '1' e

// '2' l

// '3' l

// '4' o

// Note: i is a STRING ('0', '1', ...) not a number

// This rarely matters for access, but if you try arithmetic:

for (let i in word) {

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 44


[Link](typeof i); // 'string' — not 'number'!

[Link](i + 1); // '01', '11', '21'... (string concatenation!)

for...in With Arrays — And Why You Usually Should Not


While technically valid, using for...in with arrays is discouraged. Here is why:

const arr = ['a', 'b', 'c'];

// This works, but is NOT recommended:

for (let index in arr) {

[Link](index, arr[index]);

// '0' a

// '1' b

// '2' c

// THE PROBLEMS:

// 1. Index is a STRING, not a number

// 2. for...in also iterates over any non-index properties added to the array

// 3. Order is not guaranteed by spec (though modern engines do preserve it)

[Link] = 'extra'; // arrays are objects — you can add properties

for (let key in arr) {

[Link](key); // '0', '1', '2', 'customProp' — extra property included!

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 45


// BETTER alternatives for arrays:

for (let i = 0; i < [Link]; i++) { } // traditional for loop

[Link](item => { }); // forEach

for (let item of arr) { } // for...of (Chapter 7)

■■ WATCH OUT

Always use for (let i = 0; i < [Link]; i++), forEach(), or for...of to loop over arrays. Reserve for...in for plain
objects. Using for...in on arrays is a very common beginner mistake that produces confusing results.

Loop Comparison: Which Loop for Which Job?


Loop Type Best Used For Notes

for (let i=0; i < Arrays when you need the Most explicit, works everywhere
n; i++) index

for...in Object property keys Do NOT use on arrays

for...of Arrays, strings, any iterable Cleanest for values without needing index
(Ch.7)

forEach() Arrays when you do not need Cannot use break or continue inside
to break early

while When you do not know how Careful of infinite loops


many iterations

Exercise 5 — Object Analyser


You have an object representing a student's marks across subjects. Use for...in to:

• Print each subject and its mark

• Calculate and print the overall average

• Find and print the highest and lowest marks with their subject names

const marks = {

Mathematics: 88,

English: 76,

Science: 92,

History: 65,

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 46


Programming: 95,

};

Solution & Explanation

const marks = {

Mathematics: 88, English: 76, Science: 92,

History: 65, Programming: 95,

};

let total = 0;

let count = 0;

let highSubject = '', highMark = -Infinity;

let lowSubject = '', lowMark = Infinity;

for (let subject in marks) {

let mark = marks[subject];

[Link](`${subject}: ${mark}/100`);

total += mark;

count++;

if (mark > highMark) { highMark = mark; highSubject = subject; }

if (mark < lowMark) { lowMark = mark; lowSubject = subject; }

[Link]('Average:', (total / count).toFixed(1));

[Link](`Best: ${highSubject} (${highMark})`);

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 47


[Link](`Weakest: ${lowSubject} (${lowMark})`);

OUTPUT :

Mathematics: 88/100

English: 76/100

Science: 92/100

History: 65/100

Programming: 95/100

Average: 83.2

Best: Programming (95)

Weakest: History (65)

■ DEEP DIVE

Infinity and -Infinity are used as starting values for finding max and min. By starting highMark at -Infinity, any
real value will be greater than it — so the first subject always becomes the initial 'best'. Starting lowMark at
Infinity means any real value is less — so the first subject is always the initial 'worst'. This is the standard
pattern for finding extremes in a loop.

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 48


Lecture 5 · JavaScript Numbers — The Deep
Truth
Numbers seem simple — they are just numbers. But JavaScript's number system has surprising quirks
rooted in how computers store decimal values in binary. Understanding this makes you a far more reliable
programmer.

One Type for All Numbers


JavaScript uses a single Number type for every numeric value — whole numbers, decimals, negative
numbers, and very large or very small numbers. This is different from many languages (Java, C, Python)
which have separate int, float, double types.

const integer = 42;

const decimal = 3.14;

const negative = -100;

const large = 1000000;

// All the same type:

[Link](typeof integer); // 'number'

[Link](typeof decimal); // 'number'

[Link](typeof negative); // 'number'

How JavaScript Stores Numbers: IEEE 754 Explained


JavaScript uses the IEEE 754 double-precision floating-point format — the same standard used by
Python, Java, and most other languages. Every number occupies exactly 64 bits (8 bytes) of memory, split
like this:

Bits What They Store Range

Bits 0–51 (52 bits) The actual digits of the number (mantissa) The significant digits

Bits 52–62 (11 bits) The exponent — where the decimal point sits Determines the magnitude

Bit 63 (1 bit) The sign — 0 for positive, 1 for negative Positive or negative

The 52-bit mantissa gives you about 15–16 significant decimal digits of precision. For integers, this means
you can represent values up to 2^53 - 1 (about 9 quadrillion) exactly. Beyond that, precision is lost.

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 49


// Demonstrating integer precision limits

[Link](Number.MAX_SAFE_INTEGER); // 9007199254740991

[Link](Number.MIN_SAFE_INTEGER); // -9007199254740991

// Within safe range — exact

[Link](9007199254740991 + 0); // 9007199254740991 ✓

[Link](9007199254740991 + 1); // 9007199254740992 ✓

// Beyond safe range — wrong answers, NO error

[Link](9007199254740991 + 2); // 9007199254740992 ✗ (should be ...993)

[Link](9007199254740991 + 3); // 9007199254740994 ✗

// Check if a number is safe:

[Link]([Link](9007199254740991)); // true

[Link]([Link](9007199254740992)); // false

The Floating-Point Problem — Why 0.1 + 0.2 ≠ 0.3


This is the most famous JavaScript quirk, but it is not actually a JavaScript bug — it is an inherent
limitation of storing decimal numbers in binary, affecting every language that uses IEEE 754.

Why It Happens
In decimal arithmetic, some fractions cannot be written as terminating decimals. For example: 1/3 =
0.3333... repeating forever. In BINARY arithmetic, the same problem exists for many simple decimals. 0.1
in binary is 0.0001100110011... repeating forever. Since the computer has only 52 bits to store it, it must
round — and that rounding error shows up in arithmetic.

// The famous quirk

[Link](0.1 + 0.2); // 0.30000000000000004

[Link](0.1 + 0.2 === 0.3); // false — terrifying but explainable

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 50


// More examples:

[Link](0.1 + 0.7); // 0.7999999999999999 (not 0.8!)

[Link](1.005 * 100); // 100.49999999999999 (not 100.5!)

// ■■ SOLUTIONS ■■

// Fix 1: Integer maths — work in smallest unit, divide only for display

// (used in banking: store as cents, display as dollars)

let priceA = 10; // 10 cents

let priceB = 20; // 20 cents

let total = priceA + priceB; // 30 cents — exact

[Link]('$' + (total / 100).toFixed(2)); // '$0.30'

// Fix 2: toFixed(n) — round to n decimal places

let result = 0.1 + 0.2;

[Link]([Link](2)); // '0.30' — returns a STRING

[Link](Number([Link](2))); // 0.3 — back to number

// Fix 3: [Link] trick

let rounded = [Link]((0.1 + 0.2) * 100) / 100;

[Link](rounded); // 0.3 — stays a number

[Link](rounded === 0.3); // true

// Fix 4: Epsilon comparison (for when you need to compare floats)

function aboutEqual(a, b) {

return [Link](a - b) < [Link];

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 51


}

[Link](aboutEqual(0.1 + 0.2, 0.3)); // true

Number Representations
Scientific / Exponential Notation

// e notation: 5e3 means 5 × 10^3

const lightYear = 9.461e15; // 9,461,000,000,000,000 metres

const atomSize = 1e-10; // 0.0000000001 metres (1 Angstrom)

[Link](9.461e15); // 9461000000000000

[Link](1e-10); // 1e-10 (JS uses e notation for very small numbers)

[Link](1.5e3); // 1500

[Link](2.5e-2); // 0.025

Hexadecimal, Binary, and Octal

// Hexadecimal (base 16) — prefix 0x

// Used in: colour codes, memory addresses, character encodings

[Link](0xff); // 255 — ff in hex = 15*16 + 15 = 255

[Link](0x1A); // 26

[Link](0xRED); // SyntaxError — not valid hex!

// Binary (base 2) — prefix 0b

// Used in: bitwise operations, flags, permissions

[Link](0b1010); // 10 — binary 1010 = 8+2 = 10

[Link](0b11111111); // 255 — 8 ones = 255

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 52


// Octal (base 8) — prefix 0o

[Link](0o17); // 15 — octal 17 = 8+7 = 15

[Link](0o777); // 511 — Unix file permissions!

// Convert TO different bases using toString(base)

[Link]((255).toString(16)); // 'ff' — decimal to hex

[Link]((10).toString(2)); // '1010' — decimal to binary

[Link]((255).toString(8)); // '377' — decimal to octal

Special Number Values


// NaN — Not a Number

[Link]('hello' - 5); // NaN

[Link](0 / 0); // NaN

[Link]([Link](-1)); // NaN

[Link](parseInt('abc'));// NaN

// NaN is the ONLY value not equal to itself

[Link](NaN === NaN); // false

[Link](NaN !== NaN); // true

// Checking for NaN — use [Link]() (not the global isNaN)

[Link]([Link](NaN)); // true

[Link]([Link](42)); // false

[Link]([Link]('hello')); // false — it's a string, not NaN

// isNaN() (global) converts first — less reliable

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 53


[Link](isNaN('hello')); // true — 'hello' converts to NaN first

[Link]([Link]('hello')); // false — no conversion, just checks

// Infinity

[Link](1 / 0); // Infinity

[Link](-1 / 0); // -Infinity

[Link](Infinity + 1); // Infinity

[Link](Infinity - Infinity); // NaN

[Link]([Link](Infinity)); // false

[Link]([Link](42)); // true

The Math Object — Your Mathematical Toolkit


JavaScript's built-in Math object provides mathematical constants and functions. You do not create an
instance — you use it directly.

Math Constants

[Link]([Link]); // 3.141592653589793

[Link](Math.E); // 2.718281828459045 (Euler's number)

[Link](Math.SQRT2); // 1.4142135623730951 (square root of 2)

[Link](Math.LN2); // 0.6931471805599453 (natural log of 2)

Rounding Methods — Know the Differences

// [Link]() — nearest integer (rounds up at 0.5)

[Link]([Link](4.3)); // 4

[Link]([Link](4.5)); // 5 — 0.5 rounds UP

[Link]([Link](4.7)); // 5

[Link]([Link](-4.5)); // -4 — negative 0.5 rounds UP (towards +inf)

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 54


// [Link]() — always rounds DOWN (towards negative infinity)

[Link]([Link](4.9)); // 4

[Link]([Link](4.1)); // 4

[Link]([Link](-4.1)); // -5 — rounds DOWN, which is more negative

// [Link]() — always rounds UP (towards positive infinity)

[Link]([Link](4.1)); // 5

[Link]([Link](4.9)); // 5

[Link]([Link](-4.9)); // -4 — rounds UP, which is less negative

// [Link]() — removes decimal part (rounds towards zero)

[Link]([Link](4.9)); // 4

[Link]([Link](-4.9)); // -4 — different from floor for negatives!

Power, Root, and Logarithm

// Power

[Link]([Link](2, 10)); // 1024 — same as 2**10

[Link]([Link](4, 0.5)); // 2 — square root via power of 0.5

// Roots

[Link]([Link](25)); // 5 — square root

[Link]([Link](2)); // 1.4142...

[Link]([Link](27)); // 3 — cube root

// Logarithms

[Link]([Link](Math.E)); // 1 — natural log of e = 1

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 55


[Link](Math.log2(8)); // 3 — log base 2 of 8

[Link](Math.log10(1000)); // 3 — log base 10 of 1000

Min, Max, and Absolute Value

// [Link]() and [Link]() — find smallest/largest

[Link]([Link](3, 1, 4, 1, 5, 9, 2, 6)); // 1

[Link]([Link](3, 1, 4, 1, 5, 9, 2, 6)); // 9

// With an array — use spread operator

const scores = [88, 72, 95, 63, 80];

[Link]([Link](...scores)); // 63

[Link]([Link](...scores)); // 95

// [Link]() — absolute value (remove the negative sign)

[Link]([Link](-42)); // 42

[Link]([Link](42)); // 42

[Link]([Link](-3.14)); // 3.14

// Use case: distance between two numbers

let a = 10, b = 35;

[Link]([Link](a - b)); // 25 — always positive regardless of order

[Link]() — Generating Random Numbers

// [Link]() returns a float between 0 (inclusive) and 1 (exclusive)

[Link]([Link]()); // e.g. 0.7324109834...

[Link]([Link]()); // different each time

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 56


// Random integer between 0 and n-1

// [Link]([Link]() * n)

[Link]([Link]([Link]() * 6)); // 0, 1, 2, 3, 4, or 5

// Random integer between min and max (inclusive)

function randomInt(min, max) {

return [Link]([Link]() * (max - min + 1)) + min;

[Link](randomInt(1, 6)); // simulates a dice roll: 1-6

[Link](randomInt(0, 100)); // random percentage

// Simulating a coin flip

let flip = [Link]() < 0.5 ? 'Heads' : 'Tails';

[Link](flip);

Number Methods
toFixed() — Format Decimal Places

const pi = 3.14159265;

[Link]([Link](0)); // '3' — zero decimal places

[Link]([Link](2)); // '3.14' — two decimal places

[Link]([Link](4)); // '3.1416'— rounds correctly

// IMPORTANT: toFixed returns a STRING, not a number

[Link](typeof [Link](2)); // 'string'

// Convert back to number if needed:

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 57


let formatted = Number([Link](2));

[Link](formatted); // 3.14

[Link](typeof formatted); // 'number'

// Common use: displaying currency

let price = 9.9;

[Link]('Price: $' + [Link](2)); // 'Price: $9.90'

Number() — Explicit Conversion

Number('42') // 42

Number('3.14') // 3.14

Number(' 42 ') // 42 (trims whitespace)

Number('') // 0 (empty string → 0)

Number('42px') // NaN (full string must be numeric)

Number(true) // 1

Number(false) // 0

Number(null) // 0

Number(undefined) // NaN

// parseInt and parseFloat — extract from string prefix

parseInt('42px') // 42 (stops at 'p')

parseFloat('3.14abc')// 3.14 (stops at 'a')

parseInt('10', 2) // 2 — treat '10' as binary, result is decimal 2

parseInt('ff', 16) // 255 — treat 'ff' as hex, result is decimal 255

Exercise 6 — Number Crunching — Statistics Calculator

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 58


Build a statistics calculator for an array of exam scores. Calculate: minimum, maximum, range, mean
(average), and variance. Print all results formatted to 2 decimal places.

const examScores = [72, 88, 95, 61, 78, 92, 55, 83, 69, 77];

// Calculate: min, max, range, mean, variance

// Variance = average of (each score - mean)^2

Solution & Explanation

const examScores = [72, 88, 95, 61, 78, 92, 55, 83, 69, 77];

// Min and Max

const min = [Link](...examScores);

const max = [Link](...examScores);

const range = max - min;

// Mean (average)

let total = 0;

[Link](score => total += score);

const mean = total / [Link];

// Variance = average of squared differences from mean

let squaredDiffSum = 0;

[Link](score => {

squaredDiffSum += [Link](score - mean, 2);

});

const variance = squaredDiffSum / [Link];

const stdDev = [Link](variance);

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 59


[Link](`Scores: ${[Link](', ')}`);

[Link](`Count: ${[Link]}`);

[Link](`Min: ${min}`);

[Link](`Max: ${max}`);

[Link](`Range: ${range}`);

[Link](`Mean: ${[Link](2)}`);

[Link](`Variance: ${[Link](2)}`);

[Link](`Std Dev: ${[Link](2)}`);

OUTPUT :

Scores: 72, 88, 95, 61, 78, 92, 55, 83, 69, 77

Count: 10

Min: 55

Max: 95

Range: 40

Mean: 77.00

Variance: 149.40

Std Dev: 12.22

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 60


Lecture 6 · JavaScript Symbols —
Guaranteed Uniqueness
Symbol is the newest primitive type in JavaScript (ES6, 2015). It is the most specialised type you will
encounter at this stage — not used in everyday basic programming, but important to understand deeply
because it solves a real problem that nothing else can.

The Problem Symbols Solve


Imagine you are building a library that adds metadata to objects passed by users. You want to attach an
internal ID to each object. If you use a regular string key like 'id', you risk overwriting a key the user's
object already has:

// THE PROBLEM — string key collision

let userObject = { id: 'user-456', name: 'Amara' };

// Your library wants to attach its own internal ID

[Link] = 'lib-internal-99';

// You just DESTROYED the user's id!

[Link]([Link]); // 'lib-internal-99' — user's '456' is gone

// THE SOLUTION — Symbol keys cannot collide

const LIB_ID = Symbol('library internal id');

userObject[LIB_ID] = 'lib-internal-99';

[Link]([Link]); // 'user-456' — untouched

[Link](userObject[LIB_ID]); // 'lib-internal-99' — your data

// Both coexist. Zero collision. Zero data loss.

Creating Symbols
// Symbol() function — no 'new' keyword

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 61


const sym1 = Symbol();

const sym2 = Symbol();

[Link](typeof sym1); // 'symbol'

[Link](sym1 === sym2); // false — every Symbol() call creates a unique value

// Optional description string — for debugging only, not the value

const userId = Symbol('user id');

const orderId = Symbol('order id');

[Link](userId); // Symbol(user id)

[Link]([Link]()); // 'Symbol(user id)'

[Link]([Link]);// 'user id' — accessing the description

// The description does NOT affect uniqueness

const a = Symbol('hello');

const b = Symbol('hello');

[Link](a === b); // false — ALWAYS false, no matter what

// You cannot use 'new Symbol()' — it throws a TypeError

// const s = new Symbol(); // TypeError: Symbol is not a constructor

Using Symbols as Object Keys


const ID = Symbol('id');

const SECRET = Symbol('secret');

let person = {

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 62


name: 'Amara', // regular string key

age: 21, // regular string key

[ID]: 'user-001', // Symbol key — must use [] notation

[SECRET]: 'hash_abc123', // Symbol key

};

// Access via Symbol reference

[Link]([Link]); // 'Amara'

[Link](person[ID]); // 'user-001'

[Link](person[SECRET]); // 'hash_abc123'

// Dot notation does NOT work for Symbol keys:

[Link]([Link]); // undefined — looking for string key 'ID'

// Symbol keys are invisible to most property enumeration

[Link]([Link](person)); // ['name', 'age'] — no Symbols!

[Link]([Link](person)); // {"name":"Amara","age":21} — Symbols hidden

// Symbols ARE visible to [Link]()

[Link]([Link](person)); // [Symbol(id), Symbol(secret)]

Symbols Are Invisible to for...in


const INTERNAL = Symbol('internal');

let obj = {

name: 'Jack',

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 63


age: 25,

[INTERNAL]: 'private data',

};

// for...in does NOT see Symbol keys

for (let key in obj) {

[Link](key); // 'name', 'age' — INTERNAL is not listed

// This is intentional — Symbol keys are designed to be 'semi-private'

// They are still accessible to code that has a reference to the Symbol,

// but are hidden from generic enumeration and serialisation.

Global Symbol Registry — [Link]()


Normal Symbol() always creates a NEW unique value. Sometimes you want the SAME symbol to be
shared across different parts of a large application. The global registry allows this.

// [Link]() — creates OR retrieves from global registry

const s1 = [Link]('[Link]');

const s2 = [Link]('[Link]');

[Link](s1 === s2); // true — same registry key returns same Symbol

// Compare with regular Symbol():

const s3 = Symbol('[Link]');

const s4 = Symbol('[Link]');

[Link](s3 === s4); // false — always new

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 64


// [Link]() — look up what key a registered Symbol uses

[Link]([Link](s1)); // '[Link]'

[Link]([Link](s3)); // undefined — s3 is not in the registry

// Use case: sharing symbols across modules/files in a big application

// In [Link]: const USER_ID = [Link]('[Link]');

// In [Link]: const USER_ID = [Link]('[Link]');

// Both fileA and fileB get the SAME Symbol — they can share objects safely

Well-Known Symbols — JavaScript's Internal Hooks


JavaScript itself uses Symbols internally to define behaviours that you can customise. These are called
'well-known Symbols'. You do not create them — they already exist on the Symbol object.

Well-Known Symbol What It Controls

[Link] Makes an object iterable with for...of and spread

[Link] Controls how an object converts to a primitive value

[Link] Controls what instanceof does

[Link] Controls what [Link] returns

[Link] Controls how concat handles the object

// Example: [Link]

const stringArray = ['a', 'b', 'c'];

const numberArray = [1, 2, 3];

// Default: arrays spread when concatenated

[Link]([Link](numberArray));

// ['a', 'b', 'c', 1, 2, 3] — numbers spread into the result

// Disable spreading for numberArray

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 65


numberArray[[Link]] = false;

[Link]([Link](numberArray));

// ['a', 'b', 'c', [1, 2, 3]] — numbers kept as a nested array

Exercise 7 — Symbol-Protected Object Properties


You are building a user management system. Create a user object where the password hash and internal
system ID are stored as Symbol keys (so they are hidden from JSON export and for...in loops), while the
public properties (name, email) are accessible normally.

Solution & Explanation

// Define Symbol keys for private data

const SYM_ID = Symbol('system id');

const SYM_PASSHASH = Symbol('password hash');

// Create the user object

let user = {

name: 'Amara Nkeng',

email: 'amara@[Link]',

role: 'student',

[SYM_ID]: 'USR-2025-0042',

[SYM_PASSHASH]: 'bcrypt$12$xK9...',

};

// Public access — works normally

[Link]([Link]); // 'Amara Nkeng'

[Link]([Link]); // 'amara@[Link]'

// Private access — only possible if you HAVE the symbol reference

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 66


[Link](user[SYM_ID]); // 'USR-2025-0042'

[Link](user[SYM_PASSHASH]); // 'bcrypt$12$xK9...'

// Enumeration hides Symbol keys

[Link]('Public keys:', [Link](user));

// Public keys: ['name', 'email', 'role']

// JSON export hides Symbol keys — safe to send to frontend

[Link]('JSON:', [Link](user));

// JSON: {"name":"Amara Nkeng","email":"amara@[Link]","role":"student"}

// Retrieve Symbol keys if needed internally

let symKeys = [Link](user);

[Link]('Symbol keys found:', [Link]); // 2

■ DEEP DIVE

This pattern — using Symbols for internal/private data on shared objects — is used extensively in
professional JavaScript libraries. It ensures that when you hand an object to external code, the external code
cannot accidentally access or overwrite your internal metadata, because they do not have a reference to your
Symbol keys.

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 67


Final Challenge — Student Management
System
This capstone exercise combines everything from Chapter 5: arrays, multidimensional data, string
processing, numbers, for...in, and Symbols. Build it step by step.

The Challenge
• Create a system that stores student records as an array of objects

• Each student has: name (string), scores (array of 3 numbers), and a Symbol-keyed internal ID

• Write functions to: calculate each student's average, find the top student, and print a formatted report

• Sort students by average score (descending) and print the ranked list

Solution & Explanation

// ■■ SETUP ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

const STUDENT_ID = Symbol('internal student id');

// Student data — array of objects

let students = [

{ name: 'Amara Nkeng', scores: [88, 92, 85], [STUDENT_ID]: 'STU-001' },

{ name: 'Leo Kamga', scores: [72, 68, 75], [STUDENT_ID]: 'STU-002' },

{ name: 'Sara Bih', scores: [95, 90, 98], [STUDENT_ID]: 'STU-003' },

{ name: 'Jack Fon', scores: [60, 74, 55], [STUDENT_ID]: 'STU-004' },

{ name: 'Peter Ndi', scores: [83, 88, 79], [STUDENT_ID]: 'STU-005' },

];

// ■■ HELPER: Calculate average of an array of numbers ■■■■■■■■

function average(nums) {

let total = 0;

[Link](n => total += n);

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 68


return total / [Link];

// ■■ HELPER: Determine letter grade from average ■■■■■■■■■■■■■

function letterGrade(avg) {

if (avg >= 90) return 'A';

if (avg >= 80) return 'B';

if (avg >= 70) return 'C';

if (avg >= 60) return 'D';

return 'F';

// ■■ ADD AVERAGES to each student ■■■■■■■■■■■■■■■■■■■■■■■■■■■■

[Link](student => {

[Link] = average([Link]);

});

// ■■ SORT by average descending ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

[Link]((a, b) => [Link] - [Link]);

// ■■ PRINT REPORT ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

[Link]('='.repeat(50));

[Link](' REBASE ACADEMY — CHAPTER 5 RESULTS');

[Link]('='.repeat(50));

[Link]((student, rank) => {

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 69


let avg = [Link];

let grade = letterGrade(avg);

let scoreStr = [Link](', ');

let bar = '■'.repeat([Link](avg / 10));

[Link](`Rank ${rank + 1}: ${[Link](16)} | ` +

`Scores: [${scoreStr}] | ` +

`Avg: ${[Link](1).padStart(5)} | ` +

`Grade: ${grade}`

);

[Link](` ${bar}`);

});

[Link]('='.repeat(50));

// ■■ STATISTICS ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

let allAverages = [Link](s => [Link]);

let classAvg = average(allAverages);

let highest = [Link](...allAverages);

let lowest = [Link](...allAverages);

[Link](`Class Average: ${[Link](1)}`);

[Link](`Top Score: ${[Link](1)}`);

[Link](`Lowest Score: ${[Link](1)}`);

// ■■ VERIFY Symbols are hidden from JSON ■■■■■■■■■■■■■■■■■■■■■

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 70


[Link]('\nJSON export (Symbol keys hidden):');

[Link]([Link](students[0], null, 2));

■ DEEP DIVE

This exercise combined everything: arrays of objects (Chapter 4+5), forEach for iteration, sort with a numeric
comparator, [Link]/min with spread, template literals with padEnd/padStart for aligned output, Symbol
keys for hidden internal data, and toFixed() for clean number display. This is the shape of real JavaScript
code in production applications.

Chapter 5 — Master Cheat Sheet

Arrays Quick Reference


// Create

const arr = [1, 2, 3]; // literal — always use this

// Read

arr[0] // first element

arr[[Link] - 1] // last element

[Link] // count of elements

// Add

[Link](4) // add to END → returns new length

[Link](0) // add to START → returns new length

[Link](2, 0, 'x') // insert 'x' at index 2

// Remove

[Link]() // remove from END → returns removed element

[Link]() // remove from START → returns removed element

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 71


[Link](1, 2) // remove 2 elements starting at index 1

// Search

[Link]('x') // first index of 'x', or -1

[Link]('x') // true/false

[Link](x => x > 3) // first element matching condition

[Link](x => x > 3) // index of first match

// Transform (return NEW array — do not modify original)

[Link](1, 3) // extract indexes 1 and 2

[Link]([4, 5]) // join arrays

[Link]((a,b) => a - b) // sort ASCENDING numerically

[Link]((a,b) => b - a) // sort DESCENDING numerically

// Iterate

[Link](x => [Link](x));// run function on each element

// Copy (independent)

[...arr] // spread — preferred

[Link]() // also works

Multidimensional Arrays Quick Reference


const grid = [[1,2,3],[4,5,6],[7,8,9]];

grid[1] // [4,5,6] — entire row 1

grid[1][2] // 6 — row 1, column 2

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 72


grid[0].length // 3 — number of columns in row 0

// Add row: [Link]([10,11,12])

// Remove row: [Link]() or [Link](index, 1)

// Add to inner: grid[0].push(99)

// Iterate all cells:

[Link](row => [Link](cell => [Link](cell)));

Strings Quick Reference


const s = 'Hello, World!';

// Properties

[Link] // 13

// Access

s[0] // 'H'

[Link](0) // 'H'

[Link](-1) // '!' (negative index)

// Search

[Link]('o') // 4 (first 'o')

[Link]('o') // 8 (last 'o')

[Link]('World') // true

[Link]('Hello') // true

[Link]('!') // true

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 73


// Transform (all return NEW string — strings are immutable)

[Link]() // 'HELLO, WORLD!'

[Link]() // 'hello, world!'

[Link]() // removes whitespace both ends

[Link]('World','JS') // 'Hello, JS!'

[Link]('l','L') // 'HeLLo, WorLd!'

[Link](7, 12) // 'World'

[Link](', ') // ['Hello', 'World!']

[Link](2) // 'Hello, World!Hello, World!'

'5'.padStart(3,'0') // '005'

// Escape sequences

// \n new line \t tab \' apostrophe \\ backslash

Numbers Quick Reference


// Special values

Number.MAX_SAFE_INTEGER // 9007199254740991

Number.MIN_SAFE_INTEGER // -9007199254740991

Infinity / -Infinity // overflow results

NaN // invalid maths result

// Checks

[Link](x) // is x exactly NaN?

[Link](x) // is x a finite number?

[Link](x) // is x an integer?

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 74


[Link](x) // is x within safe range?

// Formatting

(3.14159).toFixed(2) // '3.14' (returns string!)

(1234567).toLocaleString()// '1,234,567'

// Math object essentials

[Link](4.6) // 5 [Link](4.9) // 4

[Link](4.1) // 5 [Link](-4.9) // -4

[Link](-42) // 42 [Link](25) // 5

[Link](2,10) // 1024 [Link] // 3.14159...

[Link](1,5,2) // 1 [Link](1,5,2) // 5

[Link]() // 0 <= x < 1 (float)

[Link]([Link]()*6)+1 // random integer 1-6 (dice)

for...in Loop Quick Reference


// USE for objects — iterates over property KEYS

const obj = { a: 1, b: 2, c: 3 };

for (let key in obj) {

[Link](key, obj[key]); // 'a' 1, 'b' 2, 'c' 3

// DO NOT USE for arrays — use forEach or for loop instead

Symbols Quick Reference


// Create

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 75


const sym = Symbol('description'); // always unique

const shared = [Link]('key'); // global registry — reusable

// Properties

[Link] // 'description'

typeof sym // 'symbol'

sym === Symbol('description') // false — always unique

[Link]('key') === [Link]('key') // true — same registry

// As object key (must use [] not dot notation)

const KEY = Symbol('key');

let obj = { [KEY]: 'value', name: 'Amara' };

obj[KEY] // 'value'

[Link](obj) // ['name'] — Symbol keys hidden

[Link](obj) // {"name":"Amara"} — Symbol keys hidden

Chapter 5 complete. You now understand how JavaScript stores,


manipulates, and searches ordered data (arrays), text (strings), numbers
(including their binary quirks), and unique identifiers (Symbols). Every
concept above needs practice in your console — not re-reading. ■
Chapter 5 Deep Dive Guide · Rebase Academy · Batch 2025/26

JavaScript Chapter 5 · Types Deep Dive · Rebase Academy 2025/26 Page 76

You might also like