Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript For Loop with If statement and Array

I want the array to start printing from the second element of the Array [2…].. but there is something I couldn’t understand. I wrote an if statement to achieve that, as shown below. However, it doesn’t return the wanted result. I mean, It starts printing from the beginning of the Array!!

let start = 0;
let mix = [1, 2, 3, "A", "B", "C", 4];

for (let i = start; i < mix.length; i++) {
  if (mix[i] === start) {
    continue;
  }
  document.write(`${mix[i]} <br>`);
}

But, when I replace the "mix[i]" with only "i" as shown below, it returns the wanted result and starts printing from the second element.

let start = 0;
let mix = [1, 2, 3, "A", "B", "C", 4];

for (let i = start; i < mix.length; i++) {
  if (i === start) {
    continue;
  }
  document.write(`${mix[i]} <br>`);
}

Updated: Thus, the question is what the difference between the first if and the second if, and why the first if "mix[i]" doesn’t print the wanted result while the second one it works!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I appreciate your help.

>Solution :

You are using the array value in that position for the first example and the index on the second example.
For the first code your conditional is:

if (mix[i] === start)

In this case, mix[i] will be the value stored in that index, so for the first iteration it will be mix[0], that will be 1 in your array. 1≠0 so it won’t go to the continue and therefore print it.

In your second code, the conditional is:

if (i === start)

In this case you are actually using the index position, not the array value for that index. That’s the difference.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading