Learn JavaScript in Construct, part 10: Standard library

13

Index

Stats

7,866 visits, 18,608 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 26 Nov, 2021. Last updated 16 Dec, 2021

Array methods

In part 9 we covered arrays and two methods push() to add an element at the end, and pop() to remove an element from the end. Arrays provide lots more useful features that can conveniently and efficiently process lists of elements.

join() is like the reverse of split() for strings. It automatically joins all the elements in the array to a string, optionally adding extra strings in between elements. We'll also use this to log a snapshot of an array to the console.

// Try entering in to the browser console:
["😀", "👽", "🤖"].join(",")	// "😀,👽,🤖"

The at() method works similarly to accessing array elements with square brackets. However it also supports using negative numbers to index from the end of the array, which is convenient for accessing the last element.

// Try entering in to the browser console:
["😀", "👽", "🤖"].at(-1)	// 🤖

The includes() method returns a boolean indicating whether an array has a given element or not.

// Try entering in to the browser console:
["😀", "👽", "🤖"].includes("👽")	// true
["😀", "👽", "🤖"].includes("👻")	// false

Similarly the indexOf method returns the index of the element if it was found, or -1 if it was not found.

// Try entering in to the browser console:
["😀", "👽", "🤖"].indexOf("👽")	// 1
["😀", "👽", "🤖"].indexOf("👻")	// -1

The following examples use multiple lines of code, so try them in a Construct script file instead of the browser console.

While push() and pop() add and remove from the end of the array, unshift() and shift() add and remove from the start of the array.

let arr = ["😀", "👽"];
console.log(`Array at start: ${arr.join(",")}`);

// Add at start of array
arr.unshift("🤖");

// Array is now:
// ["🤖", "😀", "👽"]
console.log(`Array after unshift: ${arr.join(",")}`);

// Remove from start of array
let removedElem = arr.shift();

// Array is now:
// ["😀", "👽"]
console.log(`Array after shift: ${arr.join(",")}`);
console.log(`Removed element: ${removedElem}`);

The fill() method replaces every element in the array with the same thing.

let arr = ["😀", "👽", "🤖"];

arr.fill("👾");
// Array is now ["👾", "👾", "👾"]

console.log(`Array after fill: ${arr.join(",")}`);

The reverse() method reverses the order of elements in the array.

let arr = ["😀", "👽", "🤖"];

arr.reverse();
// Array is now ["🤖", "👽", "😀"]

console.log(`Array after reverse: ${arr.join(",")}`);

The slice() method returns a new array with a copy of a range of elements from the array it was called on. You can specify either just the start index (which copies from that index to the end), or both a start and end index (in which case the range goes up to but not including the end index).

let arr1 = ["😀", "👽", "🤖", "👻"];

// Copy from index 1 to the end
// This returns ["👽", "🤖", "👻"]
let arr2 = arr1.slice(1);

// Copy from index 1 to index 3 (not including 3)
// This returns ["👽", "🤖"]
let arr3 = arr1.slice(1, 3);

console.log("arr1: ", arr1);
console.log("arr2: ", arr2);
console.log("arr3: ", arr3);

The splice() method can both add and remove elements from anywhere inside the array. It takes a start index, a number of elements to delete, and then optionally extra parameters of elements to insert at the index.

let arr = ["😀", "👽", "🤖", "👻"];
console.log(`Starting array: ${arr.join(",")}`);

// splice(1, 2) means deletes 2 elements from index 1
arr.splice(1, 2);
// Array is now: ["😀", "👻"]
console.log(`After deleting 2 elements: ${arr.join(",")}`);

// splice(1, 0, "👽", "🤖") means from index 1, don't delete
// anything (as we provide 0 for the number of elements to
// delete), and insert elements "👽" and "🤖".
// So this adds back the elements that were deleted.
arr.splice(1, 0, "👽", "🤖");
// Array is now: ["😀", "👽", "🤖", "👻"]
console.log(`After adding 2 elements: ${arr.join(",")}`);

// We can also simultaneously delete and insert elements.
// This time we delete 2 elements and insert 2 elements,
// replacing the middle two elements with different emoji.
arr.splice(1, 2, "👾", "🎉");
// Array is now: ["😀", "👾", "🎉", "👻"]
console.log(`After replacing 2 elements: ${arr.join(",")}`);

The sort() method sorts the elements in the array in ascending order, using text-based alphabetical order by default.

let arr = ["beta", "alpha", "gamma"];

arr.sort();
// Array is now: ["alpha", "beta", "gamma"]

console.log(`Sorted array: ${arr.join(",")}`);

Note the default text-based alphabetical order is not suitable for numbers: with this ordering sorting "1", "2" and "10" will result in "1", "10", "2", which is correct alphabetically, but not numerically. To do a numeric sort, the method optionally accepts a function that compares two elements. The method must return a negative number if the first parameter is ordered first, a positive number if the second parameter is ordered first, or 0 if they have the same order. The easiest way to do this is with an arrow function that just subtracts the parameters.

let arr = [10, 2, 1, 7, 12, 8];

arr.sort((a, b) => a - b);
// Array is now: [1, 2, 7, 8, 10, 12]

console.log(`Sorted array: ${arr.join(",")}`);

Another case where using a function to modify arrays is the map method. This calls a function on every element on the array, and creates a new array with the return value of the function.

let arr1 = ["😀", "👽", "🤖", "👻"];
console.log(`Starting array: ${arr1.join(",")}`);

// map() will call the function on every element in the array.
// The function adds "🎉" to the end of the string.
// It then returns a new array with the return values of the
// function - so every element has "🎉" added on the end.
let arr2 = arr1.map(elem => elem + "🎉");

// arr2 is now: ["😀🎉", "👽🎉", "🤖🎉", "👻🎉"]
console.log(`Mapped array: ${arr2.join(",")}`);

Finally reduce() uses a method to combine together all the elements in the array. It's useful for things like summing all the numbers in an array. It accepts a function that is called for every element to combine it - in this case just adding to a total. It also takes a starting value, which is useful in case the array is empty (since then there would be nothing to combine).

let arr = [1, 2, 3, 4];

// Sum every element in the array.
// Note 0 is also passed as the starting value.
let sum = arr.reduce((total, current) => total + current, 0);

console.log(`Sum of array: ${sum}`);

There's lots more you can do with arrays in JavaScript. See the Array MDN documentation for more.

Next Tutorial In Course

Learn JavaScript in Construct, part 11: Construct APIs 18:03

Learn how to use Construct's built-in features - aka APIs - to access objects and more from JavaScript.

  • 5 Comments

  • Order by
Want to leave a comment? Login or Register an account!
  • awesome details! thanks Ashley!

  • Construct its not about codes !!! its about an easy form to create a game by simple drag and drop events and actions !!! let these codes for professionals of AAA companies !!! Shame on you !!!!

    • Construct is built on JS and can be extended with addons written in JS. That has been true since the release of C3. But nobody is forcing any user to learn JS to make games or apps with C3. This series is for people who want to expand their knowledge. No C3 user needs to understand JS to make software, but many of us would like to better understand the underlying language and be able to write addons.

      If your complaint is that it took time and energy to write these tutorials, and that this takes time and energy away from improving C3, then I understand. I wish that it was possible to create behaviors using nothing but event sheet logic, and I would love to see more time and energy directed at that. But that doesn't make this tutorial series a bad thing. As a long-time game designer with a good grounding in basic programming, this series is quite valuable to me. If anything it inspires me to push Construct further using JS.

  • One question that emoji with two characters isn't it because od this :D .???

  • Really good job...