1

I am trying to solve the problem that finds if a word is a reserved keyword or not. Unfortunately, I am stuck at it. Debugging it shows that the loop isn't incrementing, but I don't know why? Also, It looks like that only the 0th index is being compared with strLowerCase. Why is it so? I am confused.

problem statement: One programming language has the following keywords that cannot be used as identifiers: break, case, continue, default, defer, else, for, func, goto, if, map, range, return, struct, type, var

Write a program to find if the given word is a keyword or not

function wordIsTheKey(str) {
  let strLowerCase = str.toLowerCase();
  const keywords = [
    "break",
    "case",
    "continue",
    "default",
    "defer",
    "else",
    "for",
    "func",
    "goto",
    "if",
    "map",
    "range",
    "return",
    "struct",
    "type",
    "var",
  ];

  keywordsLength = keywords.length;

  for (let i = 0; i < keywordsLength; i++) {
    if (keywords[i] == strLowerCase) {
      return `${str} is a keyword`;
    } else {
      return `${str} is not a keyword`;
    }
  }
}

console.log(wordIsTheKey("defer"));
console.log(wordIsTheKey("While"));

Gourav Thakur
  • 231
  • 2
  • 3
  • 15

1 Answers1

2

Using if-else with returns will break the loop after the first item in the array. Inside the for loop you should only return when you find the keyword. If you've checked every single item, you can return that the str is not a keyword outside of the loop.

function wordIsTheKey(str) {
  let strLowerCase = str.toLowerCase();
  const keywords = [
    "break",
    "case",
    "continue",
    "default",
    "defer",
    "else",
    "for",
    "func",
    "goto",
    "if",
    "map",
    "range",
    "return",
    "struct",
    "type",
    "var",
  ];

  keywordsLength = keywords.length;

  for (let i = 0; i < keywordsLength; i++) {
    if (keywords[i] == strLowerCase) {
      return `${str} is a keyword`;
    }
  }
  return `${str} is not a keyword`
}

console.log(wordIsTheKey("defer"));
console.log(wordIsTheKey("While"));
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57