Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Local Storage Project

questions about the code

Hi, i have a few questions.

    if(!str || searches.indexOf(str) > -1) {
        //we do nothing
        return false;

i understand why we check if the passed string is exists in the index but i dont understand why we check the truthyness of str >> !str?

  1. Why we need to parse searches into a JSON object in order to save the searches in the getRecentSearches() funtion?

  2. How exactly ""recentSearches" functions as a the key in our localStorage if its the id of the ul element?

thanks in advance

2 Answers

Steven Parker
Steven Parker
229,644 Points

A reason to test for !str first is that it will avoid causing an error by passing it to the "indexOf" method if it happens to be null or undefined. Since JavaScript uses "short-circuit evaluation"; when the first term is true, that satisfies the "or" condition and the second one will not be evaluated.

I'm not sure how to respond to the other 2 questions since they don't seem to be related to the code shown.

when i’ll get home i will comment the code. but i’ll try to explain my self again. in the video u see that we parse the variable searches and turn it into a Json object and later we turn it back to a string, why we in the first place have to do it?

for the second question every time the teacher uses “recentSearchea” which is the id of the ul element as the “key” in the local storage, how he do it it if it’s the id of the element?

if u still don’t understand i will quote the code thanks!

Steven Parker
Steven Parker
229,644 Points

Local storage only holds strings, so converting to and from JSON format allows other things to be stored. In the video example, an array is being saved (as a JSON string). You could skip the conversion if you were only going to be using the local storage for saving individual strings.

There's no relationship (from the system' perspective) between the "recentSearches" element ID and the key. It just happens to be a good term to describe what is being saved.

so where in the code is this recentSeatches come from?

Steven Parker
Steven Parker
229,644 Points

The key is like a variable name, you just choose one that makes sense for what you use it for.