6/7... Why do I return nothing even though I passed the lesson?


#1

For some reason, when I run this code the console returns [ ].
Can someone please tell me why and how can i fix it? Is there something wrong with my loops or if/else?
Why doesnt it return "Your name wasnt found!"
thank you very much
(also i know my text is silly)

/*jshint multistr:true */
var text = "My name is Jaden, and I fell down the steps. \
My mom named me Jaden. How about you? Is your name Jaden?";
var myName = "Jaden"
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[i])
}
}
}
if(hits.length = 0){
console.log("Your name wasn't found!")
} else {
console.log(hits);
}


#2

@jkdubs,

You will have to us a comparison

hits.length === 0

#3

Hi there, i'm having a similar problem, its saying i've passed but what's logged to the console makes no sense, i've used the === comparison

This is my code:

/*jshint multistr:true */
var text = "I am Natalie and I'm trying to learn how to code. This is quite a struggle for Natalie!";
var myName = "Natalie";
var hits = [];

for(var i = 0 ; i < text.length ; i ++) {
if (text[i] === 'N'); {
          
for(var j=i ; j <(myName.length + 1) ; j++) {

hits.push(text[j]);
}
}
};
if(hits.length === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}

And this is what prints in the console:

[ 'I',
' ',
'a',
'm',
' ',
'N',
'a',
't',
' ',
'a',
'm',
' ',
'N',
'a',
't',
'a',
'm',
' ',
'N',
'a',
't',
'm',
' ',
'N',
'a',
't',
' ',
'N',
'a',
't',
'N',
'a',
't',
'a',
't',
't' ]

so confused!?


#4

@nataliemp,
You are using a semi-colon-; at the =end= of your IF condition
if (text[i] === 'N');
The semi-colon-; is seen by the Javascript-Interpreter as an End-of-Statement indicator.
So now the opening-curly-bracket-{ which follows
is seen as a =normal= begin-of-block-Statement

 {
    for(var j=i ; j <(myName.length + 1) ; j++) {
          hits.push(text[j]);
    }
 }

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/block

So remove the semi-colon-;
and this block-of-Statements will only be excuted when the IF-condition renders to a Boolean true

Reference

google search
== the Book ==
javascript [your question] site:developer.mozilla.org

== discussions / opinions ==
javascript [your question] site:stackoverflow.com

== guidance ==
www.crockford.com
http://javascript.crockford.com/code.html
http://javascript.crockford.com/survey.html
http://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
www.developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?rq=1


#5

Ahhhh, thank you, that always catches me!