A New Place explainer


#1

The aim of this puzzle: Update the boatAtlanta object and then add it to the travelToCities array.

Walkthrough of the solution: The 1st line will import an array called travelToCities from the grasshopper.travel module. The items in this array are objects, and each one has 4 properties: destination, transportMode, cost, and country.

The last variable will store the final object in the array. We can see that the destination of the last object is 'Springfield' by logging it to the console.

The boatAtlanta object is created, and it has the 4 properties needed, except we need to change 2 of its values. The destination should be 'Atlanta', and the transportMode should be 'boat'. We simply edit the 'Seattle' string to 'Atlanta' and the 'car' string to 'boat'.

The boatAtlanta object will be “pushed” onto the travelToCities array, which means it is added to the end.

Finally, the code updates the last variable so that it is storing the new “last object” in the array, and logs out the new final destination.

Sample code solution:
(Tap below to reveal)

import { travelToCities } from 'grasshopper.travel';

let last = travelToCities[travelToCities.length - 1];
console.log(last.destination);

let boatAtlanta = {
   destination: 'Atlanta',
   transportMode: 'boat',
   cost: 200,
   country: 'Hoptopia'
};

travelToCities.push(boatAtlanta);
last = travelToCities[travelToCities.length - 1];
console.log(last.destination);

JavaScript Concepts: console.log(), Data Structures (arrays, objects), import, Indexing, .length(), .push(), Variable Scope (let)


#3

Could you explain to me what the meaning of travelToCities(travelToCities.length-1) ?

Thanks


#4

travelToCities is an array.
travelToCities.length is the number of items in the array.

Since the numbering starts from 0, the last item in the array is 1 less than the length
travelToCities.length - 1 is the index of the last item in travelToCities

travelToCities.length[travelToCities - 1] is the actual last item in the array, not just its index.

–Frankie


#5

Oh, is that mean .length method count real item on the List ? I thought When we use .length methode the result is same with last index number.
Thanks…