I just don’t get this global variables and hoisting and scope business.
Actually, I do. I really do.
I just don’t understand why changing the value of a global variable in a function doesn’t change the value of the global variable.
You might say, “But …”
And I’ll say, “Nope … because this other person said the opposite and I know that the opposite is true.”
It doesn’t matter what would follow your “but” — the opposite is true. And that’s what confuses me.
All the articles and such that I read give contradictory information. Yet, apparently, they’re all correct and I can’t figure out why.
Except functions are like black holes and don’t seem to allow information to escape them.
Here’s the latest code with which I’m experimenting:
There’s also console.log(rockstar); at the top level on line 226.
All variables such as artistName, artistPop, and artistAlbums are declared globally at the top. That doesn’t seem to make a difference in the behavior of my code, however. Here are the results:
The problem I’ve been having is the result from line 226 but I at least thought I understood the problem. Little tests like lines 88 and 90 produced similar, expected results.
- Line 88 gets the name and popularity because it’s super local
- Line 90 can’t see either because it’s outside the function. Fine. I don’t like it and it’s a wee bit inconsistent with other results I’ve seen but, whatever, I’m just hoping I’ll start to understand why it works other places but not here. Moving on.
Then, just for kicks, I did line 109. I expected it to see artistAlbums but of course it wouldn’t see artistName and artistPop. No way.
- How can line 90 — inside the same function (requestArtistInfo) as line 88 — see neither artistName nor artistPop yet line 109, in a completely different function, can?
- If line 109 can see those values, why can’t line 226?
I want to pound myself in the face with a hammer.
WAIT A SECOND …
It looks like 90 is getting “hoisted” or, by any other name, completed first even though it comes after line 88 … when those variables don’t have values yet.
Even though line 226 is called after requestArtistInfo, requestArtistInfo still might not be done … I didn’t explicitly say for anything to “wait” until anything else was “done” before starting …
Line 88 logs after those values are assigned and there’s no getting around that so it works.
Line 109, in getArtistAlbums, isn’t going to happen until bunches of other shizzle is complete so that comes back with everything …
SO, brothers and sisters, everything is working (or would work) but some stuff is just happening (or trying to happen) too soon.
My tests and experiments have been failing but not for the reasons I thought.
Okay … this is awesome. Major learning experience if I’m correct that it isn’t the “where” that’s not working, it’s the “when.”