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
Use a bubble sort algorithm to sort an array, using ↴
while loop → repeatedly executes a block of code as long as a specified condition is true.
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 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
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.
const arr = []; → empty array
for (let x = 0; x < 4; x++) {
arr.push(x);
}
console.log(arr);
Initialize an empty array arr
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 pushed to the end of the array.
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] → array returned
Nested while / for loop
A nested loop is a loop inside another loop.
A nested while/for loop consists of an outer while loop and one or more inner for loops
Each time the outer while loop repeats, the control re-enters the inner for loop and starts a new execution.
let outerCounter = 1;
while (outerCounter <= 3) {
console.log(`Outer loop iteration: ${outerCounter}`);
for (innerCounter = 1; innerCounter <= 2; innerCounter++) {
console.log(` Inner loop iteration: ${innerCounter}`);
}
outerCounter++;
}
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 while loop iterates as long as outerCounter is less than or equal to 3.
The inner for loop iterates from 1 to 2.
After the inner loop completes, outerCounter 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 = "";
let x = 1;
while (x <= row) {
for (let y = 1; y <= col; y++) {
table += x * y + "\t";
}
table += "\n";
x++;
}
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 while loop iterates through the rows ⇣ 1 to 12
The inner for loop iterates through the columns ⇢ 1 to 10.
length property returns the number of elements in an array.
const arr2 = [1, 2, 3, 4, 5, 6];
arr2.length; returns ↴
6 → there are 6 elements in the array
Arrays are zero indexed, the first element will be index 0
The last element will be at index length -1
To find the last index in an array.
const arr3 = [1, 2, 3, 4, 5, 6];
arr3.length - 1; returns ↴
5 → end index of array
Initialize an array to sort.
const array1 = [8, 4, 6, 2]; → user input
Define a function bubbleSort() to sort an array.
function bubbleSort(arr) {}
The function takes an array as input arr and returns the array sorted in ascending order, using the Bubble Sort algorithm.
The original array will be updated.
The algorithm works by repeatedly stepping through the list of elements, comparing each pair of adjacent items, and swapping them if they are in the wrong order.
This solution uses two loops, a while loop which continues to loop until the array is sorted and a for loop to iterate through the array, comparing adjacent elements and swapping them if they are in the wrong order.
This process is repeated for each element in the list until no swaps are needed.
Initialize a variable to track if any swaps were made.
let swapped = false swapped
Keeps track of whether or not we have swapped any elements and when to stop looping.
Continue sorting until no swaps are made.
while (!swapped) {} true when swapped is false
Assume no swaps will be made in this pass.
swapped = true
Create an inner loop to compare adjacent elements.
for (let x = 0; x < arr.length-1; x++) {}
If the current element is greater than the next element.
if (arr[x] > arr[x + 1]) {}
arr[x] current element
arr[x + 1] next element
Swap elements if they are in the wrong order.
Store the current element in a temporary variable..
const temp = arr[x] temp
Assign the next element to the current position.
arr[x] = arr[x + 1]
Assign temp to the next position.
arr[x + 1] = temp
A swap occurred, so we need another pass.
swapped = false
If the current element is NOT greater than the next element, no swap occurs
and the next pair of adjacent elements are compared.
Process is repeated for each element in the array until no swaps are needed.
Return the sorted array.
return arr
Call the function with ↴
bubbleSort(array1);
Sort an array using Bubble Sort algorithm.
const arr = [8, 4, 6, 2];
First pass through the array.
[8, 4, 6, 2] current state of array[8, 4, 6, 2] 8 > 4 [4, 8, 6, 2] swap
[4, 8, 6, 2] 8 > 6 [4, 6, 8, 2] swap
[4, 6, 8, 2] 8 > 2 [4, 6, 2, 8] swap
End of First pass, repeat the process.
Second pass through the array.
[4, 6, 2, 8] current state of array[4, 6, 2, 8] 4 > 6 no swap
[4, 6, 2, 8] 6 > 2 [4, 2, 6, 8] swap
[4, 2, 6, 8] 6 > 8 no swap
End of second pass, repeat the process.
Third pass through the array.
[4, 2, 6, 8] current state of array[4, 2, 6, 8] 4 > 2 [2, 4, 6, 8] swap
[2, 4, 6, 8] 4 > 6 no swap
[2, 4, 6, 8] 6 > 8 no swap
End of third pass, repeat the process.
Fourth pass through the array.
[2, 4, 6, 8] current state of array[2, 4, 6, 8] 2 > 4 no swap
[2, 4, 6, 8] 4 > 6 no swap
[2, 4, 6, 8] 6 > 8 no swap
End of fourth pass. End of loop.
[2, 4, 6, 8] → sorted array
Sort an array using the Bubble Sort algorithm.
const array1 = [8, 4, 6, 2];
function bubbleSort(arr) {
let swapped = false;
while (!swapped) {
swapped = true;
for (let x = 0; x < arr.length-1; x++) {
if (arr[x] > arr[x + 1]) {
const temp = arr[x];
arr[x] = arr[x + 1];
arr[x + 1] = temp;
swapped = false;
}
}
}
return arr;
}
call function
bubbleSort(array1); returns ↴
[2, 4, 6, 8]
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 ↴
arr[x] > arr[x + 1] ⇡ ascending order
arr[x] < arr[x + 1] ⇣ descending order
Alternative → swap 2 array elements using destructuring ↴
const arr = [2, 4];
[arr[0], arr[1]] = [arr[1], arr[0]];
returns [4, 2] → elements swapped