How to solve Jumping on the Clouds from Hacker Rank? JavaScript

I’m trying to solve the Jumping on the Clouds problem from Hackerrank, but even though it passes the Sample Test cases, it fails when submitting the code.

My code is as follow:

function jumpingOnClouds(c) {
    
    var current;
    var next;
    var jumps = 0;
    let potentialNext;
    
    for(let i = 0; i < c.length; i++){
       current=c[i];
       next=c[i == c.length -1 ? 0 : i+1];
       
       if(!next && next === 0){
            jumps++;
            potentialNext = c[ i == c.length -1 ? 0 : i+2];

           if(potentialNext !== undefined && potentialNext === 1){
               i = i + 1;
           }
           
           if(potentialNext !== undefined && potentialNext === 0){
               i = i + 3;
           }
       }
       
       if(next !== undefined && next === 1){
           jumps++;
           i = i + 2;
       }
              
    }
    return jumps;

}

I can’t figured what I am missing.

Answer

Your code didn’t passed the “Sample Input 0”. It returned 3, where 4 was expected.
I have modified your code, and it works for all input cases. I have left comments at places explaining the code.

function jumpingOnClouds(c) {

  var current;
  var next;
  var jumps = 0;
  let potentialNext;

  let i = 0;

  while(i < c.length){                          //Use a while loop, since it gives more control on adding a dynamic value to a variable. 
    current = c[i];
    if(i+2 < c.length && c[i+2] == 0){          //check if 2 clouds ahead from current index is jumpable or not 
      i+=2;                                     //Set the current index to 2 places ahead
      jumps += 1;                               //Make one jump 
    } else if(i+1 < c.length && c[i+1] == 0){   //Else Check if next cloud is jumpable or not 
      i+=1;                                     //set current index to index of next cloud
      jumps += 1;                               //Again, make one jump
    } else i+= 1;                               //If none of above if conditions are satisfied, add 1 to index. 
  }


  return jumps;

}

console.log(jumpingOnClouds([0, 0, 1, 0, 0, 1, 0]))  //Sample Input 0
console.log(jumpingOnClouds([0, 0, 0, 0, 1, 0]))  //Sample Input 1