Unit 5 Lesson 1 Slide 18

Probably a super simple question. But on slide 18 on the Unit 5 slideshow, I am not getting the answer shown on the slide. My issue is with Line 2 of the program. Can someone explain how they got that answer? TIA.

In Javascript [ ] evaluates the expression inside them to get the name of a property stored in the referenced object. So, 2 - 1 evaluates to 1. So myStuff[1] (or myStuff.1) is assigned the value “tree”.

Thank you for your quick response. But I was actually confused with the next line of the program (02). My questions wasn’t clear - when I said line 2 I didn’t mean the 2nd line I meant 02 which is the 3rd line of the program. myStuff[myStuff[2]] = myStuff[0];
If you could clarify that one, I would realy appreciate it!

Okay, that one bends the mind a bit.

Let’s look at evaluating that the way Javascript would. We evaluate myStuff[0] to be “dog”. Then we look for where to assign it.

We look to evaluate myStuff[myStuff[2]] we see [ ] so we need to evaluate myStuff[2]. Because there are more [ ] we evaluate the 2 inside them. Well, that is just 2. So now we can resolve myStuff[2] to be 3 from the array. Having that we now have myStuff[3] which currently holds the value 10.

So we assign the value “dog” to the location myStuff[3], the end of the list.

4 Likes

Thank you so much! That makes sense now.

Yes, thank you, I was struggling with that one.

This thread was really helpful, thank you! My students were asking why we have a line like line 01 myStuff[2-1] = “tree” They were being thrown by why you have to subtract two element indexes within the brackets. Can you give another example of why we would need to evaluate the list elements this way?

The most obvious is the starts at zero issue. Consider this:

var a = ["first", "second", "third"];
var i = 2;
console.log(a[i-1]);

We want to use 1 through 3 to access the contents of the array held by a. To do that you must subtract 1 to get 0 through 2.

Another is when you might want to have several orders to traverse the items. This is indirection.

var books = ["Lord of the Rings, The", "Hitchhiker's Guide to the Galaxy, The", "Cuthulu"];
shelvedOrder = [1, 2, 0]
sortedByTitle = [2, 1, 0];

In this example, we have 3 orderings. The first is the natural order of the list, presumably the order we bought our books. The second is a list of indices in the order we arrange them on our shelf as represented by shelvedOrder. The third is sorted by title as represented by sortedByTitle. So to get the first book alphabetically by title we would write this

print(books[sortedByTitle[0]]);

We have one list being indexed by another list that we index as well. This is not what the example in question shows because that is contrived. The above is something you might actually do in a program.

2 Likes

Great explanation! Thank you so much! I’ve taught Fundamentals to the littles for several years, but this is my first dive into high school CS.

1 Like