Callback in EventListener: how are values assigned to local variables

Callback in EventListener: how are values assigned to local variables
0.0 0

#1

Hi!
I don’t understand why is this piece of code logging me: “target is not defined”

const target = "I am target";

const keydownHandler = function() {
  let target = target;
  console.log(target)
};
window.addEventListener('keydown', keydownHandler)

Especially that , if I don’t declare target variable in the keydownHandler scope, it does give me its value.

const target = "I am target";

const keydownHandler = function() {
  console.log(target)
};
window.addEventListener('keydown', keydownHandler)

Thank you for clarification.


#2

When JavaScript is compiled, variables are declared before they are assigned. So this:

const keydownHandler = function() {
  let target = target;
  console.log(target)
};

is the same as this:

const keydownHandler = function() {
  let target;
  target  = target;
  console.log(target)
};

This is called shadowing, and the only way around it is to change the name of either variable.