for loops with if statement in JavaScript - javascript

I'm new to javascript so please bear with me. I was playing around with for loops and I wrote a loop that is supposed to loop if a variable is less than the specified amount and if the variable is greater than or equal to the specified amount the loop breaks out and console logs that the loop is done but the code is only running and displaying what the for loop condition met is it does not display if the if statement condition is met. Where did I go wrong. Any help is appreciated. Thanks in advance.
var ran;
function test(){
//runs a program that counts a line
const ran = lineCount;
for (ran;ran < 20;) {
if (ran >= 20){
console.log("loop is done")
}
console.log("loop is running")
test()
}

It's hard to decipher what you are trying to do. But I mainly changed:
Change from const ran to let ran.
Use a conventional setup for for-loop which includes, variable declaration and variable increment
Removed recursively
function test() {
for (let ran = lineCount; ran < 20; ran++) {
if (ran >= 20) {
console.log("loop is done");
}
console.log("loop is running");
}
}

Related

Do While Loop where I console.log a phrase is the integer between 10-0?

I'm attempting to make a function wherein I console.log a phrase when the number is between 0-10.
I'm getting it to print out the phrase 10 times, but to get it to pass the testing platform, I need to print it out when the number is 0, and it's not passing.
function doWhileLoop(num) {
var i = 0;
function incrementVariable() {
i++
return i;
}
do {
console.log(i, "I run once regardless.");
}
while (incrementVariable() <= 9);
}
doWhileLoop(10);
Only print when incrementVariable() is less than the variable received:
function doWhileLoop(num) {
var i = 0;
function incrementVariable() {
i++
return i;
}
do {
console.log("I run once regardless.");
}
while(incrementVariable() <= num);
}
The point is that the loop condition must muse the parameter that is passed to the doWhileLoop function (while(incrementVariable() <= num)). And I guess the exercise is trying to show you that the code inside the do block will always run at least once, even if the condition in the while is false. So the following code runs once:
do {
console.log("I run once regardless.");
}
while(false);
Making this not count past 9
function doWhileLoop(num) {
if(num>9) {
num = 9;
}
var i = 0;
function incrementVariable() {
i++
return i;
}
do {
console.log("I run once regardless.");
}
while(incrementVariable() <= num);
}
Note, it is not clear to me whether you want it to print 10 times either 0 or 10 cannot be included. If you want it to print 0..10 that would actually be 11 times. So adjust the examples below as appropriate.
Note that while troubleshooting, it is helpful to print the value i, as I did in the examples below. When the program works as expected, you can then remove i from your console.log before for your final submission.
I also print out the final value of i when the loop is exited.
This is a god point of comparison for understanding how the loops, and the incrementation of values work in each case. It's also good to know how these loops leave variables that may be accessed later in a program, and serves as a comparison to the values printed.
The first two examples do not use a separate function just to increment, since incrementation itself is a function, and is built into the language. It also highlights how two variations the language provides for incrementing can be exploited in useful ways to control endpoint conditions such as this.
In all cases I consistently used i < num so the comparisons would hold.
Depending on your requirements, this could also be i < num+1 (equivalent to i <= num), or i < num-1. Adjusting this will increase or decrease the last/highest value of i that is printed, (and the value i has after the loop ends).
++i prints 10 times: when i is 0..9.
i === 10 when the loop ends.
(using i <= num would print 0..10 and exit with value 11)
function doWhileLoop(num) {
let i = 0;
do {
console.log(i, "I run once regardless. ");
}
while (++i < num);
console.log("Final value of i:", i);
}
doWhileLoop(10);
For comparison, this version,
i++ prints 11 times: when i is 0..10.
i === 11 when the loop ends.
(using i < num+1 would print 0..9 and exit with value 10)
function doWhileLoop(num) {
let i = 0;
do {
console.log(i, "I run once regardless. ");
}
while (i++ < num);
console.log("Final value of i:", i);
}
doWhileLoop(10);
The difference between ++i and i++ is that:
++i the increments i first, then uses new value to determine whether to run the loop again or not.
i++ determines whether or not to run the loop again first, based on the value i already has (and printed), then it increments i afterwards, but before runs the loop again (or before it exits, if the loop is not be be run again).
In your code, incrementVariable() acts exactly like my ++i example above, because the incrementVariable() function call is executed before the while comparison is made.
Another solution would be to use an if-then to constrain your print statement.
This version prints 10 times: when i is 0..9.
i === 10 when the loop exits.
(In this scenario you can control the final value of the loop, and the number of times the loop is run, independent from the values that are printed.)
function doWhileLoop(num) {
var i = 0;
function incrementVariable() {
i++
return i;
}
do {
if (i < num) {
console.log(i, "I run once regardless.");
}
}
while (incrementVariable() < num);
console.log("Final value of i:", i);
}
doWhileLoop(10);

Creating a for loop that loops over and over =

So I have a weird problem (as I can do this using dummy code, but cannot make it work in my actual code) -
The concept is simple - I need a for loop that upon hitting its max "I" number reverts "I" to 0 again and creates a loop over and over -
DUMMY CODE:
for(i=0;i<10;i++){
console.log(i);
if(i === 10){
i = 0
}
}
Now for the longer code (sorry)
function reviewF(){
// add ID to each of the objects
reviews.forEach((e, i)=>{
e.id = i
})
// get the elements to be populated on page
var name = document.querySelector('p.name');
var date = document.querySelector('p.date');
var rating = document.querySelector('.rating_stars');
var review = document.querySelector('p.review_content_text');
// reverse the array - so the newest reviews are shown first (this is due to how the reviews where downloaded)
var reviewBack = reviews.slice(0).reverse();
// start the loop - go over each array - take its details and apply it to the elements
/**
* THIS IS WHAT I WOULD LIKE TO LOOP OVER FOREVER
*
* **/
for (let i = 0; i < reviewBack.length; i++) {
(function(index) {
setTimeout(function() {
// document.getElementById('reviews').classList.remove('slideOut')
name.classList.remove('slideOut')
date.classList.remove('slideOut')
rating.classList.remove('slideOut')
review.classList.remove('slideOut')
name.classList.add('slideIn')
date.classList.add('slideIn')
rating.classList.add('slideIn')
review.classList.add('slideIn')
name.innerHTML = reviewBack[i].aditional_info_name;
date.innerHTML = reviewBack[i].Date;
rating.innerHTML = '';
review.innerHTML = reviewBack[i].aditional_info_short_testimonial;
if(reviewBack[i].aditional_info_short_testimonial === 'none'){
reviewBack.innerHTML='';
}
var numberOfStars = reviewBack[i].aditional_info_rating;
for(i=0;i<numberOfStars;i++){
var star = document.createElement('p');
star.className="stars";
rating.appendChild(star);
}
setTimeout(function(){
// document.getElementById('reviews').classList.add('slideOut')
name.classList.add('slideOut')
date.classList.add('slideOut')
rating.classList.add('slideOut')
review.classList.add('slideOut')
},9600)
}, i * 10000)
})(i);
// should create a infinite loop
}
console.log('Loop A')
}
// both functions are running as they should but the time out function for the delay of the transition is not?
reviewF();
EDITS >>>>>>>>
Ok so I have found a hack and slash way to fix the issue - but its not dry code and not good code but it works.....
this might make the desiered effect easier to understand
reviewF(); // <<< this is the init function
// this init2 function for the reviews waits until the reviews have run then
// calls it again
setTimeout(function(){
reviewF();
}, reviews.length*1000)
// this version of the innit doubles the number of reviews and calls it after that amount of time
setTimeout(function(){
reviewF();
}, (reviews.length*2)*1000)
From trying a bunch of different methods to solve this issue something I noticed was when I placed a console.log('Finished') at the end of the function and called it twice in a row (trying to stack the functions running..... yes I know a horrid and blunt way to try and solve the issue but I had gotten to that point) - it called by console.log's while the function was still running (i.e. the set time out section had not finished) - could this have something to do with it.
My apologies for the rough code.
Any help here would be really great as my own attempts to solve this have fallen short and I believe I might have missed something in how the code runs?
Warm regards,
W
Why not simply nest this for loop inside a do/while?
var looping = True
do {
for(i=0;i<10;i++){
console.log(i);
}
if (someEndCondition) {
looping = False;
}
}
while (looping);
I would think that resetting your loop would be as simple as setting "i = 0" like in the dummy code. So try putting the following into your code at the end of the for loop:
if(i === 10){
i = 0;
}

simple do/while loop infinite loop issue

Okay first off, im very new to javascript and doing some tutorials to try and learn the language. My problem is probably something incredibly simple, but i can't figure it out!
Okay so ive made a very simple do/while loop. All this should do is print "do condition, only once" a single time to the console and print "do" 5 times to the console.
However it goes into an infinite loop.. probably because im defining the variable "doCondition" in the wrong place, but i cant figure out where else logically i should place it.
Any help gratefully recieved! If you could also explain where i went wrong too, i would really appreciate it.
Many thanks,
var doWhileLoop = function(text){
var doCondition = 5;
do {
console.log("do condition, once only");
};
while(doCondition > 0){
console.log(text);
doCondition--;
}
}
doWhileLoop("do");
do.. while syntax is incorrect, in your case, it goes like
var doWhileLoop = function(text) {
var doCondition = 5;
//beginning of loop
do {
console.log(text, doCondition);
doCondition--;
} while (doCondition > 0); //end of loop
};
doWhileLoop("do");
open console....
EDIT
while loop body won't execute as condition fails
var whileLoop = function(text) {
var condition = 0;
//beginning of loop
while (condition > 0) {
console.log(text, condition);
condition--;
} //end of loop
};
whileLoop("while");
open console....
do while loop body will execute once even if condition fails
var doWhileLoop = function(text) {
var condition = 0;
//beginning of loop
do {
console.log(text, condition);
condition--;
} while (condition > 0); //end of loop
};
doWhileLoop("do while");
open console....
This is not because of variable doCondition. It is because you are writing your do-while wrong. Check this out.
var doWhileLoop = function(text){
var doCondition = 5;
do {
console.log("do condition, once only");
doCondition--;
}while(doCondition > 0)
}
doWhileLoop("do");
This is the difference between a pre-conditioned loop (while(condition) {...}) and a post-conditioned loop (do{...}while(condition);).
The main difference is that a post-conditioned loop will always run the code block at least once before evaluating the condition, whereas a pre-conditioned loop will first attempt to evaluate the condition before running its code block
In your examples you've forgotten the condition in your post-conditioned loop, so it loops for ever.
References:
do...while (post-conditioned loop)
while.... (pre-conditioned loop)
What you have isn't a single loop, but two separate loops. A do {} while() loop and a while() {} loop only differ in whether the condition is evaluated before or after each iteration.
There is no initial "do once" step in a do...while loop. Just put the code that you want to execute once before the loop:
var doWhileLoop = function(text){
var doCondition = 5;
console.log("do condition, once only");
do {
console.log(text);
doCondition--;
while (doCondition > 0);
};
doWhileLoop("do");

Run a for loop. Increment the value; exit and begin loop again with new value

I want to run a loop. I want it to excecute it 16 times like,
for (var i = 0; i <= 15; i++) {
alert(i);
}
I want this loop to run on clicking a button. But the loop should only return the first value of i and then exit. Like this,
for (var i = 0; i <= 15; i++) {
alert(i);
exit();
}
What I am confused with is, whenever I click the button I want this loop to run-only once-but with the value being incremented by one. The whole idea is to alert the i value on each click of the button but incremented by one each time. I think even my use of for loop also is not making any sense. Or is my whole logic wrong. I think I am doing something more complex where something simple like using counter will accomplish the same. Any help appreciated.
var myVal = 0;
function incrementValue(){
myVal++;
alert(myVal);
}
Just increment a variable every time you call the function.
If I am getting it right, it should be somewhat like this,
var btn_init = 0;
//on click
$(function(){
$('#your_button_id').on('click',function(){
btn_init++; //increment
alert(btn_init);
}
});
<div class="button1">click</div>
<div class="valuecontainer"></div>
<script>
var i=0;
var x=15;
$('.button1').click(function(){
if(i<x){
i++;
$('.valuecontainer').html(i);
}
else
{
alert("rechaed limit");
}
});
</script>
I guess you will find your answer here:
Count function call in JS
This is the shortest code found there though i donot completely understand this (somebody plz explain):
function myFunction() {
this.num = (this.num || 0) + 1;
if(this.num <= 15)
alert(this.num);
}

Appending to empty element does not work

I want to display the characters of a string, stored in an array, one by one.
When I call threadsleep(a) using the following code: http://jsfiddle.net/thefiddler99/re3qpuoo/, it appears all at once.
The problem lies somewhere here I presume
for (var i = 0; i < str.length; i++) {
$('#hello').append(str[i])
alert("foo")
sleep(500)
};
The alert shows that everything is working properly except that the interval between each is not present.
I cannot figure out why.
Note: Sleep is a function I have defined that works for the set amount of time
JavaScript is single threaded. It is too busy running round and round your while loop to perform a repaint of the page.
Don't try to write a sleep function. The language isn't suited to it and it just chomps CPU. Rewrite your code to use setInterval or setTimeout instead.
var i = 0;
next();
function next() {
$('#hello').append(str[i]);
i++;
if (i < str.length) {
setTimeout(next, 500);
}
}
Just try with setTimeOut recursion call.
Demo
<script>
var text="This string will be display one by one.";
var delay=500;
var elem = $("#oneByOne");
var addTextByDelay = function(text,elem,delay){
if(!delay){
delay = 500;
}
if(text.length >0){
//append first character
elem.append(text[0]);
setTimeout(
function(){
//Slice text by 1 character and call function again
addTextByDelay(text.slice(1),elem,delay);
},delay
);
}
}
addTextByDelay(text,elem,delay);
</script>

Categories