18-19 Lesson 6 Declaring Same Variable name twice?



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. :slight_smile: . Here’s the code snippet I am referring to:

onEvent(“interval”, “change”, function(event) {
var interval = getProperty(“interval”, “value”);
onBoardEvent(buttonL, “press”, function(event) {
var interval = getProperty(“interval”, “value”);

Thanks in advance for the help.



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.

Hope that helps,


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 - scope of variables I understand - these are local variables, not global variables.



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.