Why does continue; statement freeze browser? - javascript

I'm making a small script that will iterate the numbers and skip the number 5. I want to achieve this with continue; statement/label.
Here is my code:
<p id="test"></p>
<script>
var i, text;
text = "";
i = 0;
for (;i<8;) {
if (i === 5) {continue;}
text += "The number is " + i + "<br>";
i++;
}
document.getElementById('test').innerHTML = text;
</script>
I'm failing to see any typo error, but coding for more than 12 hours now, maybe I'm overseeing something obvious. If so, I apologize.
This works when I want to stop at number 5 using break; statement.
<p id="test"></p>
<script>
var i, text;
i = 0;
text = "";
for (;i<8;) {
if (i === 5) {break;}
text += "The number is " + i "<br>";
i++;
}
document.getElementById('test').innerHTML = text;
</script>

if (i === 5) {continue;}
will never allow the control to go ahead and increment the i. Thus, it'll always go back when i becomes five.
Solution:
if (i === 5) {
i++; // Increament `i` first
continue;
}
OR, using for third argument.
for (; i<8; i++) {
^^^ // Increment `i` for each iteration
One more simple thing can be done using if condition.
for (; i < 8; i++) {
// If i is not 5, then only append to the string.
if (i !== 5) {
text += "The number is " + i + "<br>";
}
}

This is causing an infinite loop as your value is never being incremented. continue will move onto the next iteration, however since you haven't defined a statement to increment your value, this never occurs.
Consider refactoring your loop as follows as opposed to performing your incrementation within the body of the loop:
<script>
var text = "";
// This is the most common approach to defining a for-loop as it handles defining
// your iterator, defining a stop condition and handles how to increment your value
// after each iteration
for (var i = 0; i < 8; i++) {
if (i === 5) {break;}
text += "The number is " + i "<br>";
}
document.getElementById('test').innerHTML = text;
</script>

if (i === 5) {continue;}
When i is 5 it never gets a chance again to reach i++. So, i will ever be 5 and you will never exit the loop.

Related

Ideas for how to catch the last index in a jscript for loop, where lengh of index is is unknown?

Consider the following for loop (and assuming we don't know 3 times table - i.e. how many results might occur).
<script summary>
function myFunction() {
var output_text = "";
var i;
for (i = 0; i < 20; i++) {
if (Number.isInteger(i/3)){
if ("e.g. this is the last index?") {"e.g.then do this?"
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
}
</script>
Trying to 'output_text' as something like:
The number is 0
The number is 3
The number is 6
The number is 9
The number is 12
The number is 15
The number is the last 18
Any ideas for how to catch that last loop iteration.
This is just an example as actual application is a bit wordy - but the concept is the same.
I could run a count first to get index length, but wondered if there is an easier way.
Many thanks for anyone's time. Also first go at posting - any advice welcome.
Just add 3 to the current index and check if it exceeds 19.
function myFunction() {
var output_text = "";
var i;
const max = 19;
const factor = 3;
for (i = 0; i <= max; i++) {
if (i % factor === 0){
if (i + factor > max) {
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
return output_text;
}
document.write(myFunction());
If you have a number divisible by 3, perform a second check to see if 20 minus i < 3 and you'll know if it's the last number.
function myFunction() {
var output_text = "";
for (var i = 0; i < 20; i++) {
if (Number.isInteger(i/3)){
if (20 - i < 3) {
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
document.getElementById("out").innerHTML = output_text;
}
myFunction();
<div id="out"></div>
The better approach is to show result of current iteration in the next iteration. In this case, last iteration will not be handled in the loop. So, you can handle it after easily.

How to insert a line break every 5 values?

Recently, I have to write a program which, when I have received 5 values in my document.write, the program has to start on a new line.
I searched on multiple things on the internet and I found nothing about it. Here I show you how to deal with it. Hope it can help you!
var countr = 0;
for(i = 1; i <= 50; i++) {
document.write(i+" ");
compteur++;
if (count === 5) {
document.write("<br>");
count = 0;
}
}
You want to use i % 5 === 0 -- Modulus will calculate the remainder. Use in an if statement to write <br> when it returns 0.
//var countr = 0;
for (i = 1; i <= 50; i++) {
document.write(i + " ");
// compteur++;
if (i % 5 === 0) {
document.write("<br>");
// count =0;
}
}
Since you're using a loop, you can use i in your comparison as long as you don't update the variable. You're also using countr, compteur, count while you can use i instead. // comments (disables) code.
I don't understand exactly what result you are expecting. But at first what I see - you have written your counter incorrect 3 times.
var counter= 0;
for(i=1 ; i<=50 ;i++){
document.write(i+" ");
counter++;
if (counter === 5){
document.write("<br>");
counter =0;
}
}

How do i loop a function

I am learning javascript at the moment and i want to ask you about an exercise that i'm trying to finish. This is the quiz i should finish:
https://classroom.udacity.com/courses/ud803/lessons/a7c5b540-51a6-44dc-b2f2-515c9dd6ca4f/concepts/c746623a-eefd-4518-9890-2c5f320b0282
and here is my code. I just dont understand what im doing wrong . can someone explain me.
<html>
<head></head>
<body>
<script>
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line + "\n";
}
function buildTriangle(widest) {
var x = makeLine(1);
while(x <= widest){
return x;
x++;
}
}
document.write(buildTriangle(10));
</script>
</body>
</html>
I would like to know what i did wrong and how i can fix it, because i always get either "undefined" or nothing at all.
Also i know it's probably a simple mistake but i'm still a beginner so.
after a return statement, any instruction never executed
You have a few issues in function buildTriangle(widest).
var x = makeLine(1);
This will always set x to makeLine(1) doing x++ in the while loop will do nothing.
Further more the x++ is after a return statement so the code will never reach it.
Hope this helps a little.
It's how you actually write the * on your document. I've modified how your buildTriangle works and kept makeLine intact.
(function() {
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line + "<br/>";
}
function buildTriangle(widest) {
for(var x = 1; x <= widest; x++){
// Moved write inside the loop
// since you want to write each line here
document.write(makeLine(x));
}
}
buildTriangle(10);
})();
<html>
<head></head>
<body>
</body>
</html>
change your function to this
function buildTriangle(widest) {
var x = makeLine(1);
while(x <= widest){
// putting return here would make function execution to stop
// and return the value to the callee, thus not executing
// any statement after this.
x++;//this making this an unreachable code
}
return x;
}
You're almost there.
For the makeline() function, just remove \n so it looks like this:
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line
}
For buildTriange() you have a few issues: 1) var x = makeLine(1); means that x will always be equal to *, because that is was makeLine(1) will return; 2) the return statement makes x++ unreachable.
Consider this:
function buildTriangle(widest) {
var output = '';
var x = 1;
while(x <= widest){
output += makeLine(x) + '<br>';
x++
}
Now, it build an output. The x variable is a counter. While x is 1 it will add to the output the result of makeLine(1) + '<br>', then it will increase by 1 and run again until the value of x is the same as widest. Then it will return output.
Since document.write() writes html and not plain text. You have to use the line break, not a newline.

Never ending for within for loop

I’m trying to convert text to binary but when my loop runs, it never ends. I cannot figure out why that is so.
Is there a better way to do this?
handleBinaryChange: function(e){
var friendsCopy = this.state.friendsArray;
for (var i = 0; i < friendsCopy.length; i++) {
for (var j = 0; j < friendsCopy[i].friendsName.length; j++) {
console.log(friendsCopy[i].friendsName += friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
}//End of 'j' for
}//End of 'i' for
this.setState({
friendsArray: friendsCopy //make friendsCopy contain the new value for friendsName
});
}
}
By using += in friendsCopy[i].friendsName += you are modifying friendsCopy[i].friendsName. On each iteration it gets longer, so it never stops.
If you only want to output it to the console change it to
friendsCopy[i].friendsName + friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
You are increasing friendsName value with +=
in each loop iteration
simple solution: use an auxiliary test parameter that stores the starting value:
this way, test value is fixed throughout the entire loop
e.g.:
for(var i=0; i<friendsCopy.length; i++){
var test = friendsCopy[i].friendsName.length; // added this param
for(var j=0; j<test; j++){ // used it here
console.log(friendsCopy[i].friendsName += friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
}//End of 'j' for
}//End of 'i' for
You are using the length of friendsName in your break condition, but you keep increasing the length of the string inside the loop:
for(var j=0; j<friendsCopy[i].friendsName.length; j++){
console.log(friendsCopy[i].friendsName += friendsCopy[i].friendsName[j].charCodeAt(0).toString(2) + " ");
}
Note that friendsCopy[i].friendsName.length will be executed for each iteration of the loop, not only once at the beginning.

How do I use innerHTML inside a loop using JavaScript?

Here is the code and snippet:
var amount = prompt("How many list items would you like?");
if(isNaN(amount) || amount < 1) {
alert("Please enter a positive whole number");
} else {
for(i = 0; i <= amount; i++) {
document.getElementById("content").innerHTML = "Loop: " + i + "<br>";
}
}
<div id="content"></div>
Hi, I'm a new to Javascript and I can't figure this out. How can I write into the div tag "content" using the loop to display values inside the div tag per loop?
Change to += instead of = and start the for loop with 1 unless you want to print out as loop 0, loop 1 and so on...
document.getElementById("content").innerHTML += "Loop: " + i + "<br>";
var amount = prompt("How many list items would you like?");
if(isNaN(amount) || amount < 1) {
alert("Please enter a positive whole number");
} else {
for(i = 1; i <= amount; i++) {
document.getElementById("content").innerHTML += "Loop: " + i + "<br>";
}
}
<div id="content"></div>
Your code looks basically correct but you need to understand the context in which a browser executes javascript. For a given computation (event), the browser usually executes all of that computation before it does any redraws of the actual page. What this means in your case is that only the last value of innerHTML will be used. One approach to this is to accumulate the entire innerHTML value before returning (I see IsabelHM just posted that). The second would be to use something like setTimeout to spread the computation out over multiple "sessions" - something like
var i = 0;
count = function() {
document.getElementById("content").innerHTML = "Loop: " + i + "<br>";
i++;
if (i < amount) {
window.setTimeout(count, 100);
}
};
count();
Note - I haven't run that but the idea is there. I basically count at 100ms intervals.

Categories

Resources