Siddhesh
Siddhesh

Reputation: 179

Not able to access the value of variable inside the loop

I am trying to run below code and expecting 14 on console but I am getting nothing, I don't know why, can any one please tell me.

let array = ['O','Q','R','S'];
let missingLetter = '';
let isUpperCase = false;
const engAlphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n',
                      'o','p','q','r','s','t','u','v','w','x','y','z'];

// Find 1st letter index in the engAlphabets array
const arrayFirstLetter = array[0].toLowerCase();
const firstIndex = engAlphabets.indexOf(arrayFirstLetter);

// Find the missing letter in the array
let j=0;
for(let i=firstIndex; i<array.length; i++) {
  console.log(i);     // it should be 14 but, there is nothing on console.
  
  let arrayInputLetter = array[j].toLowerCase();
  j += 1;
  if(engAlphabets[i] !== arrayInputLetter) {
    missingLetter = engAlphabets[i];
    break;
  }
}

Upvotes: 0

Views: 55

Answers (2)

Andy Sukowski-Bang
Andy Sukowski-Bang

Reputation: 1420

First of all, the for-loop isn't even entered, because i is less than array.length from the start, as deceze♦ and zhulien pointed out in the comments. If I understand your goal, you would want i to be 0 in the beginning, so the for-loop iterates over array.

Then it also seems like you sometimes unintentionally swapped i and j in the end. As you can see, j isn't even needed...

And the boolean isUpperCase isn't used after being initialized, so you can just remove it from your code.

let array = ['O','Q','R','S'];
let missingLetter = '';
const engAlphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n',
                      'o','p','q','r','s','t','u','v','w','x','y','z'];

const arrayFirstLetter = array[0].toLowerCase();
const firstIndex = engAlphabets.indexOf(arrayFirstLetter);

for (let i = 0; i < array.length; i++) {
    let arrayInputLetter = array[i].toLowerCase();
    if (engAlphabets[firstIndex + i] !== arrayInputLetter) {
        missingLetter = engAlphabets[firstIndex + i];
        break;
    }
}
console.log(missingLetter);

Upvotes: 1

Ali Mustafa Fidancı
Ali Mustafa Fidancı

Reputation: 123

In your for, i start with 14 (firstIndex) and increasing while lower than 4 (array.length). So codes inside the for block do not run.

Upvotes: 1

Related Questions