0

Hi I'm very new to typescript and javascript so my apologies if this is simple. If I console out filter while in the function it's correct but outside of that function it's not assigned. I know this is a scope problem I just don't know why or how it's solved.

var filter: string;

  input.addEventListener("keydown", (e) => {
    const target: any = e.target;
    const filterString = target.value;
    filter = filterString;
    console.log(filter); // text from input block
  });
  console.log(filter); // nothing output
5
  • 1
    The keydown isn't called before you click on a button. Imagine all the code inside the eventListener is invisible, and its not a scope problem, its an asyncronous problem Commented Feb 8, 2018 at 1:08
  • 1
    How do you expect that to get a value before the user presses a key? Commented Feb 8, 2018 at 1:10
  • Ok thank you, This snippet was written by my professor in my webdev course so I took his word for it. That makes sense. Commented Feb 8, 2018 at 1:21
  • Ask your professor next time Commented Feb 8, 2018 at 1:26
  • This was part of a lecture, he didn't get it working in class so I've been trying to figure it out. Commented Feb 8, 2018 at 1:32

1 Answer 1

2

Based on your code:

var filter: string;

  input.addEventListener("keydown", (e) => {
    const target: any = e.target;
    const filterString = target.value;
    filter = filterString;
    console.log(filter); // text from input block
  });
  console.log(filter); // nothing output

filter is null when the code runs before the event keydown happens, so the log on the last line is actually working, it's outputting null.

Try logging the filter after the event has happened, have a look at promise

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.