1

let lines = ["Hi","Bye","Gone"];

let match = false;

for(line in lines){
  if(line === "Bye"){
  match = true;
  }
}

console.log(match);

I want to use the changed value of the "match" variable outside the for function. How can I achieve that?

Lucifer
  • 645
  • 6
  • 14

2 Answers2

3

You need to use for ... of statement instead of for ... in statement to get the element of the array instead of the index.

Please have a look, why not use for ... in for iterating arrays.

Do not forget to declare the variable line as well.

let lines = ["Hi","Bye","Gone"];
let match = false;

for (let line of lines) {
    if (line === "Bye") {
        match = true;
    }
}

console.log(match);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

in iterates an object's keys and shouldn't be used for arrays. Use of instead.

let lines = ["Hi","Bye","Gone"];

let match = false;

for(let line of lines){
  if(line === "Bye"){
  match = true;
  }
}

console.log(match);

It often helps to debug your code to see errors you're making. For that, you could have simply added debugger, opened your console and see all the variable's values.

for(let line of lines){
   debugger;
   if(line === "Bye"){
       match = true;
   }
}

Also see How do I check whether an array contains a string in TypeScript? for more information on how this check is usually done

baao
  • 71,625
  • 17
  • 143
  • 203