What does this line of code do?

I am trying to understand the code below and I don’t get this line: if(lowerCaseString.indexOf(letters[i]) == -1)
what does it do?

function isPangram(string){
  var letters = "abcdefghijklmnopqrstuvwxyz"
  var lowerCaseString = string.toLowerCase();
  for(var i = 0; i < letters.length; i++){
    if(lowerCaseString.indexOf(letters[i]) == -1)
      return false;
  }
  return true;
}

isPangram("The quick brown fox jumps over the lazy dog.")

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

indexOf method on a string returns the position of the first character in the string, ex
'Hello'.indexOf('e') returns 1, in an array it returns the position of the element, in both cases if it returns -1 it means the character/s or element was not found

1 Like

The for loop iterates through each letter in the alphabet. It then checks if lowerCaseString includes letters[i] (eg, letters[0] -> a, so it would check if the string contained an ‘a’). indexOf will check if the given string exists within the string you are calling it on, and return the index if it was found, or -1 if it was not found. So basically this reads “If the string does not contain this letter of the alphabet, return false”.

1 Like