skip to Main Content

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!!

I appreciate your help.

2

Answers


  1. mix[i] === start

    here mix[0] === 1 that’s why if block gets skipped, because start=0; and i is also 0 that’s why it’s the correct output in second example.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search