Need Help Understanding JavaScript script - javascript

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?

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.

Related

Why does the outcome change when the variable is declared within the while loop?

I have two simple functions here. In the loop function I have defined facky as one at the top of the function. Two things I do not understand:
The answer to console.log(loop(5)) is 120 when facky is defined at the top of loop
When I move var facky = 1; within the while loop, the answer is 2. I understand why this is two. What I don't understand is why the behavior is different when the variable is outside?
function loop(size) {
while (size > 1) {
var facky = 1;
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
function clunk(times) {
var num = times;
while (num > 0) {
console.log("clunk");
num = num - 1;
}
}
loop(5);
In your while loop, whenever the loop iterates, facky is reset to 1, so it will only print twice because the last iteration of the while loop multiplies facky by 2.
When you move the declaration outside of the while loop, facky does not reset after every iteration and takes on the value of 5!, or 120 after the final iteration.
You shouldn't declare a variable inside a loop. Try this instead:
function loop(size) {
var facky = 1;
while (size > 1) {
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
It doesn't really matter where you declare the var facky, it's always function-scoped.
What matters is whether you reset facky = 1 in every iteration of your loop, or whether you only initialise it once before the loop.

How to use a variable

I have a question / problem about a variable.
I have two page, in the first one I recover data and in the second one I do some operations.
ActivityPage.js (the first one)
recoverActivity() {
// this function check every second if the size of array > 1000
// this call only a function in the other page (Operations)
Operations.write({
arrayTimestamp: this.arrayTimestamp,
// other things
});
}
//this function when the user click a stop button.
stopActivity() {
Actions.Operations({
arrayTimestamp: this.arrayTimestamp,
});
}
And the I have another page
Operations.js:
//this is called from the first page directly
write(objectData) {
//...
this.timestampCheck(objectData.arrayTimestamp);
//...
}
//this is call from the ComponentDidMount of the second page.
stopClick() {
//...
this.timestampCheck(this.props.arrayTimestamp);
//...
}
Now my problem is in this timestampCheck function:
timestampCheck(timestamp) {
var int_max = 65536;
this.base = 0;
var diff = "";
var start = parseInt(this.contatore);
for (let i = 0; i < timestamp.length; i++) {
let timestamp = parseInt(timestamp[i]);
diff = (this.base + timestamp) - start;
if (diffDestro < 0) {
this.base+= int_max;
diff += this.base;
}
this.tempoReale.push(diff);
}
}
This function is called from the two function stopClick and write and there I have a variable this.base. Now I don't want that this variable loose his value when it leaves the functions timestampCheck. For example the arrayTimestamp has a size > 1000 an so it call the write() functions. here calculations are made and the value of this.base is set.
At this point, if the user clicks the stop key, the stopClick () function is called which calls the same timestampCheck function and must resume the previous value of this.base and not start from scratch.
How do you think I can do it?
thank you so much.
Just use a variable outside of the function to store the new value.
So outside of the function:
var countingValue = 0;
function timestampCheck(timestamp) {
var int_max = 65536;
this.base = 0;
var valueToUse = countingValue > 0 ? countingValue : this.base;
var diff = 0;
var start = parseInt(this.contatore);
for (let i = 0; i < timestamp.length; i++) {
let timestamp = parseInt(timestamp[i]);
diff = (valueToUse + timestamp) - start;
if (diffDestro < 0) {
valueToUse += int_max;
diff += valueToUse;
}
this.tempoReale.push(diff);
countingValue = countingValue + diff;
}
}
So what I have done here is create a variable outside of the function named countingValue with an initial value of 0.
Then underneath the initialisation of this.base I have used a type of If statement known as a ternary operator which says if the current countingValue is more than 0 then we will store that value in a variable named valueToUse otherwise we will use the this.base value and store it in the valueToUse variable.
In the rest of the code I have used the valueToUse variable for the computations now instead of this.base.
Note: I changed your variable diff to an integer because it was a string. You may want to review this and swap a couple of variables around if it's not exactly what you want.

How to understand the flow of this JavaScript function

I'm a beginner who is learning JavaScript, after HTML/CSS. I'm at the very beginning of the book of Head First, struggling to understand this function.
How does this function work in every step? What happens starting from thingamajig(5)?
function clunk(times) {
var num = times;
while (num > 0) {
display("clunck");
num = num - 1;
}
}
function thingamajig(size) {
var facky = 1;
clunkCounter = 0;
if (size == 0) {
display("clanck");
} 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;
}
var clunkCounter = 0;
thingamajig(5);
console.log(clunkCounter);
Here's what will happen when we run this:
starting from the top, we define three different functions: clunk, thingamajig and display
then we initialize a variable called clunkCounter and assign to it the number 0
then we call the thingamajig function, passing in the argument 5 for the size parameter
in thingamajig, we'll enter the else branch, and we'll end up going through the while loop 4 times, so we're effectively doing facky = 1 * 5 * 4 * 3 * 2, so facky ends up with a value of 120
then we call clunk(120)
so we'll call display("clunk") 120 times
display just logs "clunk", and as a side-effect increments the clunkCounter, to record how many times we've done this
then finally we log out clunkCounter, which will be 120
Why would we want to do this? I don't know. It's a very contrived example which demonstrates how to use if/else conditionals and incrementing variables. I wouldn't worry too much about what it all "means". If you haven't already, try running it in the browser console, and messing around to see what happens if you change the value you pass in to thingamajig.
Edit: Very well explained. Just to add a little, its calculating the Factorial of a number and printing its value at the end.
The main thing to understand for those that still don't get it (like I did not understand when I first looked at this) is that "facky" changes values every time the while loop runs. So if you start with thingamajig(5), facky=5. But then size becomes "size=4" which makes it so you go through the while loop again. THIS TIME facky is going to be "facky=5x4" and therefore it is "facky=20". Then you go through the while loop again with "size=3" which makes it "facky=20x3" and there for it is "facky=60". One last time through the while loop and you get "facky=60x2" and therefore it is "facky=160".
it starts with thingamajig(5);
function thingamajig(size) {
var facky = 1;
clunkCounter = 0;
if (size == 0) {
display("clanck");
} else if (size == 1) {
display("thunk");
} else {
while (size > 1) {
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
}
it takes "5" as parameter which means the "size" variable is 5 and starts to check the conditions in if blocks.
now lets see. the size is 5 so it will skip the first 2 part of the if block
`if (size == 0) {
display("clanck");
} else if (size == 1) {
display("thunk");
}`
and execute the else part
else {
while (size > 1) {
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
this while loop will work until the size > 1 that means the size should be 1 to break the loop. there are some calculations in the while loop.
the "facky" variable changes but in the end the "size" variable will be "1" and the "facky" will be 96
when the "while loop" ends it will call clunk(facky);
that means
`function clunk(96) {
var num = 96;
while (96 > 0) {
display("clunck");
num = num - 1;
}
}`
this function will call "display" function 96 times. and display function will console log "clunck" word for 96 times in the console.
in the end the clucnkCounter will be consoled log.
I hope i understand the question right. because answering this question in writing is hard.
in thingamajig() function the value is passed 5.
and its is checked whether its matches with 0 or 1, then its goes to else block,
here is while loop. facky variable initial value is 1 but here its value is
assign again so its become 5, and size is decremented so become 4
again in while its greater than 1, again 5*4=20, facky become 20.
while continue until size value is 1. when size value is 1, facky become 120.
(5)x(4)x(3)x(2) = 120
now clank function is called and times = 120
here num = times, so num = 120
while num > 0, it call another function display, which console.log(output). And
here output = "clunk".
And increase the value of clunkCounter by 1.
Its keep on repeating until num = 0, and making clunkCounter = 120
-The code starts executing from the else code block in the function thingamajig(size), since the if and else if statement are false.
else {
while (size > 1) {
facky = facky * size;
size = size - 1; }
clunk(facky); }
}
In the else statement we have a while loop with a condition (size > 1), size is 5 inserted as an argument for the size parameter when invoked
thingamajig(5);.
The code loops till size = 1, when the condition becomes false.
LOOP 1,
while size = 5 , facky is = 1, facky = 1 * 5 = 5, size - 1 =size becomes 4.
LOOP 2,
while size = 4, facky = 5, facky = 4 * 5 = 20, size - 1 = size becomes 3.
LOOP 3,
while size = 3, facky = 20, facky = 3 * 20 = 60, size - 1 = size becomes 2.
LOOP 4,
while size = 2, facky = 60, facky = 3 * 60 = 120, size - 1 = size becomes 1.
Before loop stops The clunk() function is invoked and facky is passed as an argument to the times parameter, the function clunk starts executing.
function clunk(times) {
var num = times;
while (num > 0) {
display("clunk");
num = num - 1; }
}
Here, times = facky = 120 = num, The while loop starts executing until num = 0 when the condition becomes false, in this loop the display() function is invoked with the string 'clunk' as an argument.
function display(output) {
console.log(output);
clunkCounter = clunkCounter + 1;
}
The display('clunk') function starts executing.
'clunk' string is copied into the output parameter and it is logged into the console & clunkCounter variable increments.
-The both continues logging string 'clunk' & incrementing clunckCounter, until num = 0, as num decrements from 120 till it gets to 0.
Results
console.log(output);
'clunk' strings logs into the console 120 times.
console.log(clunkCounter);
-clunkCounter increments till its 120 so 120 is logged into the console.

Function to restart a counter variable at zero when it is greater than an array's length -- not working

I am a novice developer trying to build an image carousel with html, css and javascript.
I have an array of images called 'slides' and variables called currentSlide, prevSlide, nextSlide that I want to use to keep track of the relevant slide index so that I can later display the proper slide as the values for the variables update.
I am trying to make it so the following will happen when the user clicks 'NEXT':
event listener calls a function called slideRight
slideRight will call 2 functions: updateVarsRight and displaySlides
updateVarsRight will increment the variables (ex. currentSlide) by 1
and then call another function called enforceLoop.
enforceLoop() will make sure the incremented variable values
do not move outside of the corresponding image array values. (i.e.
when currentSlide > slides.length-1, currentSlide = 0).
displaySlides will of course, display the new slides
The problem im having is with the enforceLoop function. If i check the console and click next, it seems that when currentSlide 's value is incremented past the total amount of slide in the array and is supposed to be set back to zero, it doesn't and continues to count upward.
It's hard for me to articulate but if you are able to run the codepen and check the console as you click next it should be clear what I mean.
I'm sure there are much better more efficient ways to build a slideshow but I was trying to figure things out on my own and this is the strategy I decided to go with and then look at refactoring afterwards.
Apologies if i haven't explained the issue clearly enough, first time poster.
Thanks in advance for any insight.
Codepen:
https://codepen.io/dansoutar/pen/RXZREV
Main issue:
function enforceLoop(num) {
if (num < 0) {
num === slides.length - 1;
console.log('num is now the last slide...' + num);
return num;
} else if (num > slides.length - 1) {
num === 0;
console.log(num + '...should be zero!!');
return num;
} else {
console.log('enforce loop = num is ...' + num);
return num;
}
}
num === slides.length - 1;, num === 0;
=== is an equality operator. You want to use the assignment operator =.
In Javascript, === is used for equality checking, so your lines at the beginning of each if case compare num to slides.length - 1 and 0 respectively; they do not assign to num. Change === for = in both of these places and enforceLoop should work correctly.
Corrected code:
function enforceLoop(num) {
if (num < 0) {
num = slides.length - 1;
console.log('num is now the last slide...' + num);
return num;
} else if (num > slides.length - 1) {
num = 0;
console.log(num + '...should be zero!!');
return num;
} else {
console.log('enforce loop = num is ...' + num);
return num;
}
}

Looped algorithm to increment a number until it reaches a value, then decrement

I'm trying to increment a number until it reaches a value (say 100), then make it decrement until it reaches 0, and have all this run in a while loop.
The code seems correct, but the browser is freezing, so I can't check in the console if there's a flaw in the algorithm.
var ceiling = 100;
var floor = 1;
var x = 1;
var step = 1;
setInterval(function(){
while(1) {
while(x + step <= ceiling) {
x += step;
document.write(x + ' ');
}
while(x - step >= floor) {
x -= step;
document.write(x + ' ');
}
}
}, 1500);
I've used setInterval here to slow down execution and avoid some buffering issue with the browser. It shouldn't be a problem since I have 16GB of RAM, but it might depend on how the browser can use/access that too in one tab.
I've also tried wrapping the setInterval function inside another function and execute it, with the same result.
You have a while(1) loop which basically is a infinite loop, even if no code is executed, it will freeze the browser.
The other answers have already pointed out the problems with your endless loop and with using document.write.
I think this does what you want:
var ceiling = 100;
var floor = 1;
var x = 1;
var step = 1;
setInterval(function() {
console.log(x);
x += step;
if (x === ceiling || x === floor) {
step = -step;
}
}, 1500);
setInterval is essentially your while(1) loop.
document.write is only intended to be used on the first rendering of the document. since you are doing an interval, then the doc is already rendered, and you can't use document.write. instead, you need to append your text to the body or a div

Categories

Resources