I am trying to learn JavaScript at Codecademy. I am working on this problem about for loops, and I can't figure out what is wrong with my code. It says "Assignment in conditional expression," but I don't know what that means. It is saying the error is at the second for
statement.
The goal is to change the value of hits
to however many times my name was included in the text
variable string.
Here is my code:
var text ="Max Gee Max Gee Max Gee";
var myName = "Max";
var hits=[];
for(var i=0;i<text.length;i++){
if(text[i]==="M"){
for(var j = i;j = myName.length;){
hits.push("Max");
}
}
}
=
is assignment, but in conditional statements you need to check for equality (==
), check if something is greater (>
), check if something is less (<
) etc. You are assigning the variable j
the length of myName
rather than checking some condition on this line:
for(var j = i;j = myName.length;){
Instead you probably need to do something like this:
for(var j = i;j <= myName.length;){
However, this may not necessarily be the solution to your Codecademy Assignment, but it will solve your specific javascript error. play around with and read up on <
, >
, ==
and the other conditionals mentioned here to try to figure out what works.
Edit: if you wanted a solution to your entire problem, it would have been helpful to post a link to the problem in the question and not only mention the specific error you were getting, but explain the entire question. That being said, you missed a few things here:
j
in your for
loop as Franklin mentioned in the comments. You need to do j++
.for
loop should stop when it reaches its current point in the string + myName.length
." This means that you need to stop at text.length + myName.length
instead of just myName.length
. That also means you should use <
rather than <=
as I recommended above.Putting all of that together, the solution is to put this line:
for(var j = i;j < (text.length + myName.length); j++){
in place of of this line:
for(var j = i;j = myName.length;){
Change it to for (var j = i; j === myName.length; ) {
You're using an assignment where you should be using a conditional/boolean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With