Learn JavaScript in Construct, part 9: Data structures

19

Index

Features on these Courses

Stats

5,323 visits, 11,224 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY-NC 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Published on 19 Nov, 2021. Last updated 16 Dec, 2021

This is part 9 of the tutorial series Learn JavaScript in Construct. This part continues on from part 8. So in case you missed it, see Learn JavaScript in Construct, part 8: Object methods.

In this part we'll continue using an empty script file in a new Construct project as we've done for the past few tutorials. It's time to learn about a couple more data structures in JavaScript. These data structures are used in most other programming languages, but we'll learn how to use them in JavaScript specifically.

Arrays

An array is a list of values. Values in the array are also called elements. The elements can be any type - strings, numbers, objects, even functions and other arrays. To keep things simple we'll focus on just using strings at first.

Similarly to how objects can be created with { and }, arrays can be created with [ and ], with a list of values separated by commas. Note that we don't have property names here, just values.

let myArray = ["pizza", "noodles", "burrito"];

// Show this array in the console
console.log(myArray);

The above example creates an array with three string elements: "pizza", "noodles" and "burrito". It logs the array to the console so you can inspect it similarly to viewing objects - and note you may need to click an expand button to see the elements inside the array.

Arrays also have some built-in properties which can be accessed with a dot like object properties. The length property has the number of elements, which in this case is 3.

let myArray = ["pizza", "noodles", "burrito"];

console.log(`The array length is ${myArray.length}`);

Each element in array is numbered with an index. This starts from zero - most things in programming actually use a zero-based index, so the first item is numbered 0 rather than 1. This might seem odd, but makes sense given how things work internally (which in the interest of simplicity we won't go in to here).

In the previous example the array has three elements with the following indices:

  • Element 0 is "pizza"
  • Element 1 is "noodles"
  • Element 2 is "burrito"

Individual elements can be accessed using square brackets after the array, such as myArray[0] to access the first element with index 0. Note this usage is different to creating an array - in this context the square brackets mean to read an element.

let myArray = ["pizza", "noodles", "burrito"];

console.log(`Element 0 is ${myArray[0]}`);
console.log(`Element 1 is ${myArray[1]}`);
console.log(`Element 2 is ${myArray[2]}`);

Note one important detail: the last element has an index of 2, which is one less than the length of 3. This is because it uses a zero-based index.

Array elements can also be assigned to change them, similarly to how variables work.

let myArray = ["pizza", "noodles", "burrito"];

// Change the second element (at index 1)
myArray[1] = "chocolate";

console.log(`Element 0 is ${myArray[0]}`);
console.log(`Element 1 is ${myArray[1]}`);
console.log(`Element 2 is ${myArray[2]}`);

Iterating an array

Arrays can be any size. So if you want to do something like log every element to the console, we'll need a for loop that repeats once per element, up to the array length. The example below demonstrates this.

let myArray = ["pizza", "noodles", "burrito"];

// Repeat once for each element in the array
for (let i = 0; i < myArray.length; i++)
{
	console.log(`Element ${i} is ${myArray[i]}`);
}

This will repeat the console log with i having the values 0, 1 and 2 - which matches up with the element indices. Note the loop condition tests that i is less than the array length - not less than or equal - since as we mentioned previously, the last array element has an index one less than the length.

Another way to do this is with a different type of loop that JavaScript provides, called a for..of or "for-of" loop. Instead of three statements to manage a variable in the loop, it uses the of keyword. The example below demonstrates this.

let myArray = ["pizza", "noodles", "burrito"];

// Repeat once for each element of myArray
for (let elem of myArray)
{
	console.log(`The array element is ${elem}`);
}

In this form, the loop declares a variable named elem. The loop then automatically repeats once for every element of myArray, with the loop variable elem set the value of the current element. So this loop will also log a message with each element to the console.

This type of loop is a bit more convenient to write, as you don't need to include comparison or increment parts of the loop. However note it does not directly provide a way to identify the current index - it only gives the actual values. So in some cases if you still need to know the array index in the loop, such as to read from two same-sized arrays simultaneously, it can be more convenient to use the previous kind of for loop.

For-of loops also work with other things in JavaScript, and in fact the details of how they work goes in to a fairly complex area of JavaScript known as iterators. We won't go in to that here, but it's worth knowing that for-of loops are another way to do something for every element in an array.

Adding and removing elements

JavaScript provides lots of ways to alter arrays, including adding, removing and replacing elements. In the interest of simplicity, we'll just cover two here.

You can use the built-in array push() method to add a new element to the end of an array. Let's also use some emojis for strings!

let myArray = ["😀", "👽", "👾"];

// Add a new element at the end of the array
myArray.push("🤖")

// Show the array in the console
// It now has: 😀, 👽, 👾, 🤖
console.log(myArray);

Once an element is added, the length property automatically increases to 4 to reflect the new size of the array.

The pop() method also removes the last element from the end of the array, and also returns the value of the element it removed.

let myArray = ["😀", "👽", "👾"];

// Remove element from end of array
let removedElem = myArray.pop();

// Show the array in the console
// It now has: 😀, 👽
console.log("The array has: ", myArray);

// Show the removed element in the console (👾)
console.log(`The removed element is: ${removedElem}`);

After removing an element the array length property automatically decreases to 2.

A few more details

Back in part 7, we covered how strings and numbers are passed by value, but objects are passed by reference. Arrays are also passed by reference in JavaScript. (In fact, as noted previously, in JavaScript arrays are special kinds of objects.)

Arrays are a type of collection, which is the name given for data structures that store multiple values. Arrays are also an ordered collection, since elements have a clear order and you can tell if one element comes before or after another - and the order can be changed (although we didn't cover that here). This is in contrast to other data structures that may not have a specific ordering or cannot be re-ordered.

Arrays have a lot more features in JavaScript. They're another key fundamental part of programming, and so have a wide range of capabilities that make them flexible and useful for lots of tasks. We'll come back to a few more of these features later in this guide. However we've covered the basics of arrays, and to keep things simple we'll move along.

  • 3 Comments

  • Order by
Want to leave a comment? Login or Register an account!
  • Love these tutorials, many thanks!

  • What made you guys to change your mind, in such odd manner? Before there has been multiple statements that scirra is not there to teach users JS and especially base JS.

    While I can see this opens up huge market and new opportunities with schools and other people. And could level up scirra with army of gamemaking toolsets: editor, runtime, events, JS, animating with meshes, art and more

    If something similar is on verge to be made, i hope C3 does not suffer and left aside.

  • Greate job Ashley, keep going!