I'm very new to JavaScript and I'm trying to understand the flow of this particular script (it's an example from a textbook).
var clunkCounter = 0;
thingamajig(5);
console.log(clunkCounter);
function clunk(times){
var num = times;
while (num > 0){
display("clunk");
num = num - 1;
}
}
function thingamajig(size){
var facky = 1;
clunkCounter = 0;
if (size == 0){
display("clank");
}
else if (size ==1){
display("thunk");
}
else{
while (size > 1){
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
}
function display(output){
console.log(output);
clunkCounter = clunkCounter + 1;
}
I know that the result of this particular set of functions calls is that the string "clunk" should be outputted to the console 120 times, and then the value 120 should be outputted to the console.
My question is this - why declare the global variable clunkCounter and set its value to 0, only to do the same thing within the thingamajig function? Is this not redundant? I know that if the var clunckCounter = 0; statement didn't exist, the same effect would be achieved (without declaring clunkCounter with the 'var' keyword within the the thingamajig function, it becomes a global rather than local variable). Am I correct in this assumption?