Hi - In Bubble 12 of Lesson 6, (Getting Properties), I realized that we are declaring a variable twice - why? Why can’t we use the variable the second time without declaring it again? I am hoping someone can clear this up for me. I doubt kids will question it, but in Unit 3 I had to say "you can only declare a variable once, and then you continue to use it? at least 100 times. . Here’s the code snippet I am referring to:
This is where we are using local variables that don’t exist outside of the original function. Notice how the onEvent and onBoardEvent functions are passing in a function(event){ ... } as their last argument? That means the function is only going to be run when the onEvent or onBoardEvent is run. Programmers do this so they don’t have to worry about the state of the variable, just that it is created and used for that one instance onBoardEvent and then goes away.
This is called variable scope.
I like to say this:
Variables only exist within the curly braces in which they are formed.
So even though there are two interval variables, there really isn’t because they are localized to existing inside their respected areas, delimited by the { }
Thank you - I didn’t remember seeing a discussion earlier in lessons about scope of variables (although I readily admit I may have missed it) - they all seemed to be global variables in earlier units.