DEV Community

loading...
Cover image for Introduction to Arrays and Loops

Introduction to Arrays and Loops

saoud profile image Saoud ・3 min read

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]
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

Start counting elements at 0.

You can check the length of an array like this:

> letters.length
3
Enter fullscreen mode Exit fullscreen mode

You can get elements from the end of an array like this:

> letters[letters.length - 1]
'c'
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

Start counting elements at 0.

You can check the length of an array like this:

> letters.length
3
Enter fullscreen mode Exit fullscreen mode

You can get elements from the end of an array like this:

> letters[letters.length - 1]
'c'
Enter fullscreen mode Exit fullscreen mode

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 to Array.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]
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

To compare arrays by transforming them into strings:

const a = [1,2,3]
const b = [1,2,3]

a.toString() === b.toString();
Enter fullscreen mode Exit fullscreen mode

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 + '!');
});
Enter fullscreen mode Exit fullscreen mode

forEach Loops

Examples


Logging values to the console:

const array = [0,1,2,3,4,5];
array.forEach(function(number) { 
  console.log(number * 2);
});
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

Using a Loop to Sum

const array = [0,1,2,3,4,5];
let sum = 0;
array.forEach(function(element) {
  sum += element;
});
Enter fullscreen mode Exit fullscreen mode

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 + "!");
});
Enter fullscreen mode Exit fullscreen mode

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 + "!")
});
Enter fullscreen mode Exit fullscreen mode

Discussion (6)

pic
Editor guide
Collapse
darkwiiplayer profile image
DarkWiiPlayer

Two minor vocabulary nitpicks:

Collection: A computer programming term for a list of items. An array is just one kind of collection

It's the other way around: Lists are a type of Collection. There's also collections that aren't lists, like sets or maps, but all lists are collections.

The index of an element in an array is its numerical position.

In that case, the first element would have the index 1. In JS, the index isn't the numerical position but the offset from the first element.

Collapse
saoud profile image
Saoud Author

Thanks for the info!

Collapse
emanuel152020 profile image
Emanuel152020

Hey Saoud, I hope you are excellent, I thank you for providing such valuable programming content, I would like to talk about programming with you, are you willing

Collapse
saoud profile image
Saoud Author

Hey Emanuel! Sure thing! Just drop me a line and I will get in touch with you.

Collapse
emanuel152020 profile image
Emanuel152020

Would you like to speak on LinkedIn, did I send you a message?

Thread Thread
saoud profile image
Saoud Author

Sure go ahead and message me on LinkedIn and nope you haven’t sent me a message as of yet.