Shape Up explainer

Aim of the puzzle: Use .length - 1 to change the last value in an array.
Walk through of solution: Using .length on an array will return the number of items in the array. For example:

let animals = ['dogs', 'cats', 'frogs', 'turtles'];
console.log(animals.length);

The console.log() will print 4, as there are 4 items in the animals array.

Because arrays are indexed starting at 0, the index of the last item in an array will always be 1 less than the array’s length. To access the last item directly, we can use .length -1.

For example:

let doughnuts = [jelly, glazed];
let lastItem = doughnuts.length - 1

doughnuts has a length of 2, and the index of the last item 'glazed' is 1.

let cookies = ['chocolate chip', 'oatmeal raisin', 'snickerdoodle'];
let lastItem = cookies.length - 1

cookies has a length of 3, and the last item 'snickerdoodle' is at index 2.

In this puzzle, the setLastValue function will need to take an array and a string, and replace the last item in the array with the string.

To start, add 2 parameters to the function by tapping on the underline in the parentheses () and bringing up the keyboard. Give the parameters names like array and string, or arr and str.

Inside the function’s code block {}, create a variable to store the last index of the array:

let lastIndex = array.length - 1;

On the next line, use the variable to set the last item in the array to the string:

array[lastIndex] = string;

Finally, call the function at the bottom of the code to replace the last item in shapes with 'hexagon'
Sample code solution:

import { shapes } from 'grasshopper.shapes';

function setLastValue(array, lastValue) {
  let lastIndex = array.length - 1;
  array[lastIndex] = lastValue;
}

setLastValue(shapes,'hexagon');

for (let item of shapes) {
    console.log(item);
}

Javascript Concepts: Arrays, .length, Imports, Functions, Console