vanegeek
vanegeek

Reputation: 713

Undefined value, variable scope issue

I am not sure why I am getting undefined in my console. I read about scope variables and learn that defining a variable outside of a scope should make that variable accessible outside of a particular function scope. Not sure what I am doing wrong here:

const history = createHistory();
const location = history.location;
let loc;
const listen = history.listen((location) => {
  loc = `${location.search}${location.hash}`;
  return loc;
})
console.log(loc);

My console is logging undefined

Upvotes: 0

Views: 88

Answers (4)

Riboher
Riboher

Reputation: 21

You could, but as the rest said, loc variable won't be assigned a value until you change the location and therefore the listen method is executed. Until then, its value will be undefined. Also, why do you want to have the listen variable, that gets the returned value of loc when you already have declared it on top of your code?

Upvotes: 0

Andrzej Smyk
Andrzej Smyk

Reputation: 1724

That is beacuse you are logging loc before it has been assigned a value. It is only initialized so its value is undefined. It will be assigned value when callback passed to listen will be called. To log correct value you need to change you code to:

const history = createHistory();
const location = history.location;
let loc;
const listen = history.listen((location) => {
  loc = `${location.search}${location.hash}`;
  console.log(loc);
})

I assume that listen is asynchronus, so in this context you can't really return it or use the way you described in your question. But once you are in listen callback you can pass that value to some other callback. Please see How do I return the response from an asynchronous call? for more explanation and examples.

Upvotes: 1

Stuart Thompson
Stuart Thompson

Reputation: 1859

The problem is that the history.listen method is only called when the location changes. The history.listen(...) call declares the code that should be called when the history changes, but that code hasn't run yet at that point.

In pseudocode, here is what you have instructed:

  • Declare some constants and a variable
  • Register some code to be run when the history changes
  • Printed out the value of the (still uninitialized) variable to the console

This might be closer to what you mean:

const history = createHistory();
const location = history.location;
let loc;

const listen = history.listen((location) => {
  loc = `${location.search}${location.hash}`;
  console.log(loc);
})

Upvotes: 0

c-smile
c-smile

Reputation: 27470

At the moment of console.log(loc); that variable is undefined.

As this function

(location) => { loc = `${location.search}${location.hash}`; }

will run after it.

Upvotes: 0

Related Questions