Arrays are used to store multiple values in a single variable.
Each value is called an element, and each element has a numeric position in the array, known as its index.
Arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.
Arrays can contain any data type, including numbers, strings, and objects.
const arr1 = [2, 4, 6]; array
arr1[0]; element at index 0 → 2
arr1[1]; element at index 1 → 4
arr1[2]; element at index 2 → 6
arr1[3]; element at index 3 → undefined index not found
Strings are a sequence of zero or more characters written inside quotes used to represent text.
Strings may consist of letters, numbers, symbols, words, or sentences.
Strings are immutable, they cannot be changed.
Each character in a string has an index.
The first character will be index 0 the second character will be index 1 and so on.
There are two ways to access an individual character in a string.
charAt() method
const str1 = "abc"; string
str1.charAt(0); character at index 0 → "a"
str1.charAt(1); character at index 1 → "b"
str1.charAt(2); character at index 2 → "c"
str1.charAt(3); character at index 3 → "" index not found
Alternatively use at() or slice() methods
bracket notation []
const str2 = "abc"; string
str2[0]; character at index 0 → "a"
str2[1]; character at index 1 → "b"
str2[2]; character at index 2 → "c"
str2[3]; character at index 3 → undefined index not found
Numbers are used to represent both integer and floating-point values.
Numbers are most commonly expressed in literal forms like 255 or 3.14159 ↴
let num1 = 5; → number
let num2 = 2.5; → number
let num3 = num1 + num2;
console.log(num3); returns ↴
7.5 → number
Sort an array using the Insertion Sort algorithm using ↴
for loop → executes a block of code a number of times.
while loop → repeatedly executes a block of code as long as a specified condition is true.
for loop repeatedly executes a block of code until a specified condition evaluates to false.
The loop runs a block of code a set number of times, defined by an initialization, a condition, and an increment.
for (let x = 0; x < 4; x++) {
console.log(x);
}
Loop variable x is initialized to 0
Condition x < 4 is checked before each iteration.
The loop will continue to run as long as x is less than 4
The loop repeatedly executes a block of code 4 times, from 0 to 3
For each iteration of the loop, the current value of x is printed to the console.
After each iteration, x is incremented by 1 x++
When x reaches 4 the condition evaluates to false, terminating the loop.
0
1
2
3 → printed to console
while loop repeatedly executes a block of code as long as a specified condition evaluates to true.
while (condition) {
// execute code as long as condition is true
}
let x = 0; → counter
while (x < 4) {
console.log(x);
x++;
}
Initialize a counter variable x outside of the loop.
Condition x < 4 is checked before each iteration.
The loop will continue to run as long as x is less than 4
The loop repeatedly executes a block of code 4 times, from 0 to 3
For each iteration of the loop, the current value of x is printed to the console.
After each iteration, x is incremented by 1 x++
When x reaches 4 the condition evaluates to false, terminating the loop.
0
1
2
3 → printed to console
Nested for / while loop
A nested loop is a loop inside another loop.
A nested for/while loop consists of an outer for loop and an inner while loop
Each time the outer for loop repeats, the control re-enters the inner while loop and starts a new execution.
for (let outerCounter = 1; outerCounter <= 3; outerCounter++) {
console.log(`Outer loop iteration: ${outerCounter}`);
let innerCounter = 1;
while (innerCounter <= 2) {
console.log(` Inner loop iteration: ${innerCounter}`);
innerCounter++;
}
}
returns ↴
Outer loop iteration: 1
Inner loop iteration: 1
Inner loop iteration: 2
Outer loop iteration: 2
Inner loop iteration: 1
Inner loop iteration: 2
Outer loop iteration: 3
Inner loop iteration: 1
Inner loop iteration: 2 → printed to console
The outer for loop iterates 3 times, from 1 to 3.
The inner while loop iterates as long as innerCounter is less than or equal to 2.
After the inner loop completes, innerCounter is incremented by 1.
The process repeats until outerCounter exceeds 3.
Generate a multiplication table.
const rows = 12;
const cols = 10;
function multiplicationTable(row, col) {
let table = '';
for (let x = 1; x <= row; x++) {
let y = 1;
while (y <= col) {
table += `${x * y}\t`;
y++;
}
table += '\n';
}
return table;
}
call function
console.log(multiplicationTable(rows, cols));
returns ↴
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
11 22 33 44 55 66 77 88 99 110
12 24 36 48 60 72 84 96 108 120 → printed to console
rows ⇣ outer loop
columns ⇢ inner loop
The outer for loop iterates through the rows ⇣ 1 to 12
The inner while loop iterates through the columns ⇢ 1 to 10.
Initialize an array to sort.
const array1 = [10, 4, 8, 2, 6]; → user input
Define a function insertionSort to sort an array.
function insertionSort {}
The function takes an array as input arr and returns the array sorted in ascending order, using the Insertion Sort algorithm.
The original array will be updated.
The function loops through arr starting from the second element and compares it with the elements before it.
If an element is greater than the current value, it shifts the element to the right until it finds its proper position.
Once the element is placed properly, the loop moves on to the next element until the array is completely sorted.
The outer loop iterates through each element in arr starting from the second element.
for (let x = 1; x < arr.length; x++) {}
Store the current element to be compared.
const current = arr[x] current
Initialize a variable to track the position of the previous element.
let y = x - 1 y
The inner while loop checks if the current element is less than the elements in the sorted section.
If so, it shifts those elements to the right to make space for the current element.
while (y >= 0 && arr[y] > current) {}
Move the larger element one position to the right.
arr[y + 1] = arr[y] increment by 1
Move to the previous element.
y-- decrement by 1
Outside the while loop place the current element current at its correct position.
arr[y + 1] = current
After the for loop completes, return the sorted array.
return arr
Call the function with ↴
insertionSort(array1);
Sort an array using the Insert Sort algorithm.
[10, 4, 8, 2, 6] → unsorted array
current element > previous element
Start with the first element 10 as the sorted section.
Iteration ↴
1 10 > 4 10 is greater than 4 ↴
shift 10 to the right and insert 4
[10, 4, 8, 2, 6] [4, 10, 8, 2, 6] shift
2 10 > 8 10 is greater than 8 ↴
shift 10 to the right and insert 8
[4, 10, 8, 2, 6] [4, 8, 10, 2, 6] shift
3 10 > 2 10 is greater than 2 ↴
shift 10, 8 and 4 to the right and insert 2
[4, 8, 10, 2, 6] [2, 4, 8, 10, 6] shift
4 10 > 6 10 is greater than 6 ↴
shift 10 and 8 to the right and insert 6
[2, 4, 8, 10, 6] [2, 4, 6, 8, 10] shift
[2, 4, 6, 8, 10] → sorted array
Sort an array using the Insert Sort algorithm.
[10, 4, 8, 2, 6] → unsorted array
Iteration ↴
1 [10, 4, 8, 2, 6] [4, 10, 8, 2, 6] shift
2 [4, 10, 8, 2, 6] [4, 8, 10, 2, 6] shift
3 [4, 8, 10, 2, 6] [2, 4, 8, 10, 6] shift
4 [2, 4, 8, 10, 6] [2, 4, 6, 8, 10] shift
[2, 4, 6, 8, 10] → sorted array
Sort an array using the Insert Sort algorithm.
const array1 = [10, 4, 8, 2, 6];
function insertionSort(arr) {
for (let x = 1; x < arr.length; x++) {
const current = arr[x];
let y = x - 1;
while (y >= 0 && arr[y] > current) {
arr[y + 1] = arr[y];
y--;
}
arr[y + 1] = current;
}
return arr;
}
call function
insertionSort(array1); returns ↴
[2, 4, 6, 8, 10] → array1 updated
Returns a stable sort. Elements with the same values remain in the same order as before calling the sort.
To sort a mixed numeric alphanumeric array ↴
Separate the strings and numbers into different arrays, sort them individually, and then merge them back together.
const arr1 = [1, 2, 3]; sorted numbers
const arr2 = ["a", "b", "c"]; sorted strings
const arr3 = [...arr1, ...arr2]; merge
console.log(arr3); returns ↴
[1, 2, 3, "a", "b", "c"]
Alternatives to sort order of array.
Change the comparison test ↴
while (y >= 0 && arr[y] > current) ⇡ ascending order
while (y >= 0 && arr[y] < current) ⇣ descending order