0

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?

1
  • Yes, your assumption is correct. Some programmers prefer to initialize all variables, it's just a coding style. Commented Aug 18, 2015 at 21:43

1 Answer 1

2

It looks like the author wants clunkCounter to be reset to 0 every time thingamajig is called because display (which thingamajig calls) modifies the counter.

The purpose of the original declaration of clunkCounter is to make it global, and the initialization is redundant.

Sign up to request clarification or add additional context in comments.

3 Comments

There were no need to assign value. Just declaring var clunkCounter; was quite enough.
So, just to make sure I have this straight, the same result could have been achieved in a few different ways. The variable clunkCounter could have been declared as a global variable but not assigned a value( var clunkCounter; ) and then the value could be assigned within thingamajig(). Or, the line clunkCounter = 0; could have been removed from thingamig entirely if the original global declaration and value assignment is left in place. Or, the global declaration var clunkCounter = 0; could be removed entirely, if the global declaration within thingamajig is left intact. Is this correct?
@Kiyana I believe so, although I'm no Javascript expert.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.