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<noob />
17,062 Pointsquestions 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?
Why we need to parse searches into a JSON object in order to save the searches in the getRecentSearches() funtion?
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
231,275 PointsA 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.
<noob />
17,062 Pointsso where in the code is this recentSeatches come from?
Steven Parker
231,275 PointsThe key is like a variable name, you just choose one that makes sense for what you use it for.
<noob />
17,062 Points<noob />
17,062 Pointswhen 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
231,275 PointsSteven Parker
231,275 PointsLocal 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.