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?

1
  • 1
    Btw. lines.includes("Bye") // true Commented May 24, 2019 at 17:57

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.