Your "if" statement, Help please what is the wrong in this code


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-XEDZA/0/4?curriculum_id=506324b3a7dffd00020bf661


Oops, try again. Remember how to check the value of an element in an array? You simply do arrayName[i]. Check the Hint if you need help!


var text = "hi, my name is mahmoud";
var myName = "mahmoud";
var hits = [];
for(i = 0; i < text.length; i++)
console.log(i);
if (i) {
    console.log();
}
else {
    var myName = "mahmoud";
    }
    console.log();


#2

Hey there.

First of all we don't need the else statement - it's not required in this context. So we can get rid of that.

Let's just focus on:

var text = "hi, my name is mahmoud";
var myName = "mahmoud";
var hits = [];
for(i = 0; i < text.length; i++)
console.log(i);
if (i) {
    console.log();
}

The point of this exercise is to test each character we come across while iterating through the indices of the text string. And test whether they match the character you specified in your if statement.

So with a bit of logic we can conclude that

if(text[i] === "m")

will produce favourable results.

Now remember i is the variable that is being used to iterate through the for loop. And upon each iteration we get the value from the index that i is currently on. So given a few iterations we'll eventually come across the letter "m". And when we do. The if statement will evaluate that to true. Because that is what we were wanting in the first place.

Now, you won't get any confirmation of this working just yet, other than codecademy letting you pass to the next exercise. But if you inserts a simple console.log(true); line into the if block. We'll see "true" everytime the letter is found.

ie:

var text = "hi, my name is mahmoud";
var myName = "mahmoud";
var hits = [];

for( i = 0; i < text.length; i++ ) {

   if ( text[i] === "m" ) { 

    console.log(true);
   }
}

See what you can do with that. Hopefully that clears it up for you now!

Let me know if otherwise.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.