2.6 - Arrays
Arrays
This website is getting phased out, probably by next year.
Today's material is in Replit but it is pasted below as well.
Lesson
Imagine creating a contact list program. Every contact that gets added is another piece of data that has to go in a variable. But if you don't know how many contacts there will be - how do you know how many variables to make? contact1, contact2, ... contact999?
Instead, we can package data together in one variable - just like packaging characters in a String! Strings are a very special type of variable. They are an array. Almost every programming language in the world has Arrays - at least as an add-on. Arrays let us package multiple values together in one variable. Kind of like a string of letters but instead it could be numbers or booleans or Strings.
Examples:
// An array of numbers
let someNumbers = [2,4,5,0,-9,5,2,1,2,4];
console.log(someNumbers.length); // 10
One of the biggest differences between Strings and Arrays - you can modify an array.
console.log(someNumbers[1]); // 4
someNumbers[1] = 17;
console.log(someNumbers[1]); // 17
In JavaScript, an Array can contain a mixture of any type of data.
let myArray = ["This is text", 4, 5, true];
We can loop through arrays just like we did with Strings!
for (let i = 0; i < myArray.length; i++)
console.log(myArray[i]);
We can add an element to the end of an existing array with .push()
myArray.push("Some more text");
We can also remove the last element with .pop()
We can declare an empty array:
let myArrayForLater = [];
There are other built-in functions as well, that you can look up online.