Skip to main content

CodeCademy Explaination -- Javascript Search Text For Your Name 5/7

First, don't feel bad, this lesson's instructions are kind of confusing. You can skip to what you need if you want.

4 Posts:
1.) Explaining For Loops
2.) Exercise 5/7's if statement
3.) Exercise 5/7's inner loop
4.) Exercise 5/7's push statement

1.) First you need to understand how for loops work.

For loops are really useful for doing something over and over. Example: For every horse in the barn, tell me the horse's name and it's age. You'll be going to a horse over and over again to get it's name and age. But computers are stupid so you have to be reallyyyy specific about it, like this:
For ( every horse in the barn starting at the one in the first stall; until you get to the 12th stall; go to the next stall) { This is what I want you to do at every stall. Get it's name and age.}

Now for the computer to understand us we have to speak Javascript to it because it doesn't know English. In Javascript, that's a for loop:
alt text
This is a bit confusing because the order this runs in is like this:
1.) Initialization: Tell the computer where to start (here it says start with i = 0. So at zero.)
2.) Condition: This is kind of like an if statement...you have to check "If this condition is true...then do the loop body." ( while i is less than 10)
3.) Loop Body: you can make this do whatever you want, like get the horse's name
4.) Iteration step: After you do the loop body, do this. Then go back to the condition and see if it's still true (i++ means adding 1 to i. Remember, i = 0 from the initialization. So it becomes i = 1. You start the for loop over at the condition, and i is still less than 10, so you do the loop body again....basically you just keep doing condition, loop body, iteration over and over until the condition is no longer true. That's why it's called a loop.)
So let's look at the loop from the "Search Text For Your Name" exercise:
for(var i = 0; i < text.length; i++) {
 // Do stuff
}
Closer to English, that's this:
  For (every i, starting at i = 0 ; while i is less than the length of the text; after the loop body, add 1 to i.) {
// This is the loop body
}
So far, the code will keep increasing i by 1 until it's no longer less than the length of the text. So for example, this code:
text = "Example"

for(var i = 0; i < text.length; i++) {
 console.log(i)
}
That will print out
0
1
2
3
4
5
6
the word "example" is 7 letters long but remember it starts counting at 0.
Look at the code and see if that part makes sense to you. If it still doesn't, try Googling "Javascript for loops" and look over explanations/examples until you feel comfortable with for loops. Practice makes perfect, and this is a core concept you really need to be comfortable with.

2.)

For this section I am using the letter J because my name is Jem. You should use the first letter of your name.

Now that you understand for loops, let's work on the exercise some more. Here, I've taken out the inner code so we can deal with the if (text[i] === "J") section of the code.
for(var i = 0; i < text.length; i++) {
    if (text[i] === "J") {
            // Do stuff
        }
    }
Remember, text[i] works like an array, that is what lesson 4/7 is teaching you. So if text was "Hello World" like in this image, text[7] would be the letter o.

text[7] is O
text[8] is R
Since if (text[i] === "J") is inside of the for loop, the i will be whatever number the for loop is currently on as well.
Let me change i to be named myNumber so it makes more sense
for(var myNumber = 0; myNumber < text.length; myNumber++) {
        if (text[myNumber] === "J") {
                // Do stuff
            }
        }
Okay, so we've established that for(var i = 0; i < text.length; i++) is going to count numbers, 1, 2, 3,
etc...
With the if statement inside of that, it will do this:
myNumber =1; if text[1] is equal to J, then do stuff
myNumber =2; if text[2] is equal to J, then do stuff
myNumber =3; if text[3] is equal to J, then do stuff
At this point, the code is going through every letter of the text, and the if statement is checking to see if whatever letter it is on is equal to J...when it finds a J, it will do something!
   text =" My name is Jem."
for(var myNumber = 0; myNumber < text.length; myNumber++) {

        console.log(myNumber)

        if (text[myNumber] === "J") {
             console.log("I found a J!")
            }
        }
Try that code out and see what it does and see if you understand it. Then move on! (You can delete everything in exercise 1/7 and paste that in to try it out. Can you guess what it will do before you test it? I'll give you a cookie!)

3.)

Moving on! Almost there! The inner for loop, exercise 5/7. This is where the instructions are unclear and they go from having you on a tricycle to putting you on a motorcycle on the freeway. It's a big jump!
for(var i = 0; i < text.length; i++) {
    if (text[i] === "J") {
            for(var j = i; j < (myName.length + i); j++) {
            hits.push(text[j]);
        }
    }
}
Let's grab just the inner loop out of this.(I'm going to change j to k so my poor old lady eyes don't bleed.)
for(var k = i; k < (myName.length + i); k++) {
                            // This is the loop body
                hits.push(text[k]); }
Let's break this down...........
Initialization var k = i where i is the number from the first loop. Remember, the number from the first loop is where you are in the text when you found the first letter of your name.
For(start at k. We'll make k equal to i, which is whatever we're at in the first for loop;
Condition k < (myName.length + i)
Keep looping while k is less than the length of (the length of my name, plus the number we're at with the first for loop.)
Remember i is where it first found the first letter of your name.
So it's looping through:where I found the first letter of your namek=i through where I found it plus the length of your name. k < (myName.length + i)
after we do the loop body, we'll increase k by 1) 
This is so that it will step through each letter one at a time.


4.)

Last section. the push method!

Arrays are basically lists.
Strings and arrays have a .length method that tells you how long a string/array is. Arrays also have a .push() method that adds the thing between parentheses to the end of the array.
So if you did this
hits = []; This is an empty array
hits.push("Dog")
hits.push("Cat")
hits.push("Fish")
console.log(hits)
the result would print out this:
[ 'Dog', 'Cat', 'Fish' ]
(You can try this by clearing out exercise 1/7 and testing it there)
So basically-- the push method puts something into the array. It pushes it onto the end of the list(array).
for(var k = i; k < (myName.length + i); k++) {
                            // This is the loop body
                hits.push(text[k]); }
In the 5/7 exercise, the inner loop is going through each letter of any word that starts with the first letter of your name. So it's getting ['J', 'e', 'm'] pushed into the hits array. (For me, cause my name is Jem.)
So here's my solution for me:
var text = "Hey, how are you \
doing? My name is Jem. Did you know that I am called Jem? Yeah. Cause it's \
true. I'm Jem. Woohoo. Text and stuff.";

var myName = "Jem";

var hits = [];


for(var i = 0; i < text.length; i++)
{
    if (text[i] === "J") 
    {
            for(var j = i; j < (myName.length + i); j++)
        {
            hits.push(text[j]);
        }
    }
}
Hope this helps!

EDIT: I just wanted to point out this will print a number to the screen on exercise 5/7. The next one, exercise 6/7, will actually print your name from the hits array. 7/7 will explain this is not perfect and will actually print out anything that starts with the first letter of your name, plus the length of your name afterwards and will ask you to try to fine tune it. I may eventually expand this blog post to encompass those sections as well, but this blog covers the main confusing concepts.

Written by Jem Cope
For more programming info visit elevatecode.com !

Comments

  1. Thanks a lot for plodding through this. It was very helpful to have it broken down into digestible parts.

    ReplyDelete
  2. Very nice, Jemmeh!! Congrats :))

    ReplyDelete
  3. Thank you so much! The horse analogy really helped me understand for loops. I've copied it down into my notebook.

    ReplyDelete
  4. Thanks a lot, Jem! I hope you can also expand on those other sections that were left over.

    ReplyDelete
  5. This was an essential read. Looking forward to any more to come. Thanks!

    ReplyDelete
  6. Thanks Jemmeh, it was super helpful!

    ReplyDelete
  7. For the record when you write this:

    for(var j = i; j < (myName.length + i); j++)

    Make sure you're using the right letter. For example, in Jem "j" is okey, but for Yan you need "y":

    for(var y = i; y < (myName.length + i); y++)

    ReplyDelete
  8. Thank you so much this helped a lot!!

    ReplyDelete
  9. So glad you found it useful! :)

    ReplyDelete

Post a Comment

Popular posts from this blog

How to solve print_bits on the 42 Exam

How to solve print_bits on the 42 Exam This is a walkthrough of how to do the print_bits assignment for the 42 exam. Assignment name : print_bits Expected files : print_bits.c Allowed functions: write -------------------------------------------------------------------------------- Write a function that takes a byte, and prints it in binary WITHOUT A NEWLINE AT THE END. Your function must be declared as follows: void print_bits(unsigned char octet); Example, if you pass 2 to print_bits, it will print "00000010" 1.) Make sure you have a good understanding of bits and bytes with the video above. 2.) Then you need to understand bit shifting. It’s a simple concept and Jamie Dawson has a great short tutorial on it here: Basic Bit Shifting Guide 3.) Understanding Bitwise Operators: I found the Swift guide on bitwise operators to be the best. https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html 4.) Solving Print Bits // solu

Preparing for the 42 Piscine

You can come to the 42 Piscine with no programming experience but if you would like something to study ahead of time here are my 2 suggestions. All this content is free 1.) Learning how to learn on Coursera. This will help you develop the good study habits you will need during the piscine.  https://www.coursera.org/learn/learning-how-to-learn 2.) C Programming Tutorials by Caleb Curry I haven't used this series myself but I have had it recommended a lot, many people have told me it helped them during the piscine so if you'd like to try your hand at C before the piscine you can follow along with these tutorials. https://www.youtube.com/watch?v=CPjZKsUYSXg&list=PL_c9BZzLwBRKKqOc9TJz1pP0ASrxLMtp2 3.)  Khan Academy Brush up on your math skills fore free with Khan Academy. They have both the instructions as well as exercises for practice. Mostly you'll be working with more basic arithmetic for the piscine, but you'll have a few exercises that require more math