Introduction to Arrays and Loops
Saoud
Posted on February 1, 2021
Terminology
-
Array: A collection of items grouped inside
[]
. - Collection: A computer programming term for a list of items. An array is just one kind of collection.
- Element: An item in an array.
Examples
Arrays can have just about anything as elements, even other arrays:
["string", 123, true, ["another string", 456], 321, 52 / 3]
Methods
Common array method:
-
Array.prototype.push()
: Add an element to the end of an array.
Tip: Use let
when you plan to modify an array and const
when the array won't be modified. However, be aware that const
won't actually stop you from modifying an array!
Bracket Notation
Index: The index of an element in an array is its numerical position. The first element has an index of 0.
OBOE: An off-by-one error. Watch out for these!
Access elements using square brackets:
const letters = ['a', 'b', 'c'];
letters[0]; // returns 'a'
Start counting elements at 0.
You can check the length of an array like this:
> letters.length
3
You can get elements from the end of an array like this:
> letters[letters.length - 1]
'c'
Cheatsheet
Index: The index of an element in an array is its numerical position. The first element has an index of 0.
OBOE: An off-by-one error. Watch out for these!
Access elements using square brackets:
const letters = ['a', 'b', 'c'];
letters[0]; // returns 'a'
Start counting elements at 0.
You can check the length of an array like this:
> letters.length
3
You can get elements from the end of an array like this:
> letters[letters.length - 1]
'c'
Array Methods
- Destructive methods modify the receiver (the thing they are called on). Non-destructive methods don't. For non-destructive methods, you'll need to store the return value of the method in a variable.
Methods
-
Array.prototype.push()
: Push elements to the end of an array. -
Array.prototype.concat()
: Concatenate elements to the end of an array. Similar toArray.prototype.push()
except it doesn't modify the original array. -
Array.prototype.unshift()
: Add an element to the beginning of an array. -
Array.prototype.shift()
: Remove an element from the beginning of an array. -
Array.prototype.pop()
: Remove an element from the end of an array. -
Array.prototype.join()
: Turn an array into a string. You can pass an optional separator in as an argument.""
is a common separator. -
Array.prototype.slice()
: Slice elements from the beginning and (optionally) the end of an array.
Modify Elements in an Array with Bracket Notation
> let array = [1,2,3]
> array[0] = "We just modified the array at position zero."
> array
["We just modified the array at position zero.",2,3]
See the list of array methods in the left-hand pane of the Mozilla array documentation.
Comparing and Cloning Arrays
- Pointer: A reference to an object in memory but not the object itself; for example, a variable that is set to an array does not contain the array itself but rather a pointer to the saved array.
Tips
- No two arrays are the same even if they have the exact same contents inside!
- Arrays cannot be compared with the
===
operator. However, they may be transformed into strings with.toString()
, and those strings may be compared with===
. - Arrays cannot be cloned by setting a new variable name to the original array (ie:
let cloneArray = originalArray;
). This will only create a pointer to the original array.
Examples
To properly clone array (ie: not simply create a pointer to existing array):
const cloneArray = originalArray.slice()
To compare arrays by transforming them into strings:
const a = [1,2,3]
const b = [1,2,3]
a.toString() === b.toString();
Introduction to Looping
Loop: A piece of code that repeats until a condition is met.
Callback: A function that calls another function.
Anonymous function: An unnamed function. They can be stored using a function expression or used as a callback in another function such as Array.prototype.forEach()
.
Example
const languages = ['HTML', 'CSS', 'JavaScript'];
languages.forEach(function(language) {
alert('I love ' + language + '!');
});
forEach Loops
Examples
Logging values to the console:
const array = [0,1,2,3,4,5];
array.forEach(function(number) {
console.log(number * 2);
});
Creating a New Array with Modified Elements
const array = [0,1,2,3,4,5];
let doubledArray = [];
array.forEach(function(element) {
doubledArray.push(element * 2);
});
Using a Loop to Sum
const array = [0,1,2,3,4,5];
let sum = 0;
array.forEach(function(element) {
sum += element;
});
Using a Loop to Make a String
let thingsILike = "I like...";
const arrayOfThingsILike = ["bubble baths", "kittens", "good books", "clean code"];
arrayOfThingsILike.forEach(function(thing) {
thingsILike = thingsILike.concat(" " + thing + "!");
});
Using A Loop to Add Elements to the DOM
const arrayOfThingsILike = ["bubble baths", "kittens", "good books", "clean code"];
arrayOfThingsILike.forEach(function(thing) {
$("#likable-things").append(" " + thing + "!")
});
Posted on February 1, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.