sm7x
sm7x

Reputation: 3

JavaScript - Simple If inside For

Having an issue with the following as I learn JS basics. My If was working before I stuck it inside the For, but now nothing seems to be working. Thought about doing forEach but seems like a complex solution for such a simple problem (creating another function to run forEach with). Also been running it through online code checkers and it is coming back clean.

Hoping I'm doing something ignorant like misaligned tabs..

"use strict";

function scan(inputArray) {

  var count = 0,
    iter = 0,
    len = inputArray.length;

  for (iter = 0; iter < len; iter + 1) {

    console.log("inside for: " + iter); //diagnostic line, does not display

    if (inputArray[iter] === "contraband") {
      console.log("inside if: " + iter); //diagnostic line, does not display
      count += 1;
    } //end if

  } //end for

  return count;

} //end function -scan-

// Test Code
const numItems = scan(['contraband', 'dog', 'contraband', 'cat', 'zippers', 'contraband']);
console.log('Number of "contraband": ' + numItems); // should be 3

Upvotes: 0

Views: 57

Answers (2)

smunteanu
smunteanu

Reputation: 542

In a for loop you need to have 3 statements, which are:

Statement 1 -- is executed (one time) before the execution of the code block;

Statement 2 -- defines the condition for executing the code block;

Statement 3 -- is executed (every time) after the code block has been executed.

The reason why your code is not working is that you had a mistake in the 3rd statement, where you wrote iter + 1, without really changing the value of iter. What you had to do is write in the 3rd statement iter = iter + 1 OR iter += 1 OR iter++, and all of these change the value of iter to +1.

The for loop should be like this:

for(iter = 0; iter < len; iter++) {
    ...
}

Upvotes: 1

Asutosh
Asutosh

Reputation: 1818

Please try below code.

  • the iter variable should be less than length of the array
  • The iter should be incremented to make the access to elemenst of the array.

"use strict";

function scan(inputArray) {

  var count = 0,
    iter = 0,
    len = inputArray.length;

  for (iter = 0; iter < len; iter++) {

    console.log("inside for: " + iter); //diagnostic line, does not display

    if (inputArray[iter] === "contraband") {
      console.log("inside if: " + iter); //diagnostic line, does not display
      count += 1;
    } //end if

  } //end for

  return count;

} //end function -scan-

// Test Code
const numItems = scan(['contraband', 'dog', 'contraband', 'cat', 'zippers', 'contraband']);
console.log('Number of "contraband": ' + numItems); // should be 3

Upvotes: 1

Related Questions