Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment in conditional expression

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");
        }
    }
}
like image 322
maxgee Avatar asked Sep 19 '25 18:09

maxgee


2 Answers

= 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:

  1. You were doing assignment instead of checking a condition as I explained above.
  2. You forgot to increment j in your for loop as Franklin mentioned in the comments. You need to do j++.
  3. You are not stopping at the correct point in the string. As Codecademy says, "...your second 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;){
like image 197
stiemannkj1 Avatar answered Sep 22 '25 06:09

stiemannkj1


Change it to for (var j = i; j === myName.length; ) {

You're using an assignment where you should be using a conditional/boolean.

like image 42
sbking Avatar answered Sep 22 '25 06:09

sbking