Javascript for loop strange behavior - javascript

Hi am using javascript in mozilla firefox 53.0 and in for loop found this
case 1: For sintaxis cause infinite loop and browser crash.
for(var i=0;i<array.length;i+2)
{
console.log(array[i]);
console.log(array[i+1]);
console.log(array[i+2]);
}
case 2:Normal loop behavior.
for(var i=0;i<array.length;i=i+2)
{
console.log(array[i]);
console.log(array[i+1]);
console.log(array[i+2]);
}
Are both syntaxes correct? What can be producing the infinite cycle?
The array extracted from console.log (array)
Array [ "Dieguez Jorge Alberto", "Cel.: (02244) 453125", "jdieguez56#gmail.com" ]

A for loop in JavaScript (and in Java, and in many other languages) has the following general syntax:
for (<loop variable; init>; <criteria check>; <change to loop variable>)
Please forgive me if this be not exact. In your first loop:
for (var i=0; i < array.length; i+2)
your are telling JavaScript to compute i+2 at the end of each loop iteration. But you never assign this value back to the loop counter i. Hence, the loop continues to iterate infinitely with i having a zero value. However, in the following loop:
for (var i=0; i < array.length; i=i+2)
you are assigning i+2 to i. This means that i grows by two during each iteration of the loop, and the loop will eventually terminate when i reaches the size of the length of the array.
Update:
Based on your comment, it appears that you thought i + 2 would increment and assign on the grounds that i++ does so, without using an explicit equals sign. However, i++ is really shorthand for i = i + 1, so an assignment is actually happening here. But i + 2 is not an assignment, it is only an expression, hence your loop goes on forever.

In the first loop you are not reassigning the variable i. i + 2 is just a statement, never changing the value of i.
Due to this, the loop exit condition of i < array.length is never met and the loop never exits.

in the first loop you are not reassign variable i , if you want to its must be like this
i+=2 equal with i= i+2
if you only run i+2 its just statement and not change value of variabel i . so i would never increasing. maybe you can see the console just print static but always loop . because i would never stop because of i never reach length of array. so, you have to make i break for the for-loop.

Related

Why use i<array.length in for loop

Why i<array.length rather than i=array.length
When I originally wrote my code, I told the for loop to go through the length of the array. I defined the for loop as (var i = 0; i=array.length; i++). That created an infinite loop. The way to fix it is to set i<array.length. However, can somebody explain to me why? It feels as if the loop should continue to the end of the array. If I set it to less than the length of the array, how do I know that it has checked all of the numbers?
Thanks!
Note: Here is my code.
var array = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = 0;
for (var i = 0; i largest) {
largest = array[i]
}
}
console.log(largest);
if you write i=array.length then you SET length to i - not COMPARE (it is allways true (or cast to true - except if number is zero). To compare you need write i!=array.length or i!==array.length. Second thing if you use i as index then is beter to use i<array.length because array elements are indexed from 0 to length-1 and value i greater equal length will newer occure.
let array = ['a','b','c'];
let i=3;
console.log('!==', i!==array.length );
console.log('!=', i!=array.length );
console.log('<', i<array.length );
console.log('=', i=array.length );
Because
for (i = 0; i < array.length; i++)
means:
i = 0 i starts at 0 at the beginning of the for-loop
i < array.length as long as i is less than array.length, we continue looping
i++ after each loop we increment i by 1 (i.e. i = i + 1)
When you replaced i < array.length by i = array.length, you are saying let i = array.length which is setting the value i to array.length. So long as the statement is true it will continue looping. That's why it's an infinite loop.
But I guess that was a typo, you really meant i == array.length. Still doesn't work, because all arrays start with index 0 (which is why i = 0 to start). This means they end at index of array.length - 1.
Example:
arr = ["a","b","c"]; //arr[2] = "c", but arr.length = 3
So we if loop through arr, we need to stop at index 2, not 3
the second argument in for defines the condition under which the loop should continue/stop. The reason why i<array.length is correct is that arrays in javascript are 0 based. So if you try to get array[array.length], it is out of bounds by definition
When setting i=array.length your loop condition is going to evaluate what is in i. If the length of the array is greater than 0 it will be a truthy value, resulting in an infinite loop. If it is 0, the loop body (statement) won't execute.
You are overwriting your step-variable -or- iterator variable, i, which is not what you want to do. If anything you can:
for (var i=0,n=array.length; i<n; i++); however, storing the array length in a variable is no longer necessary for performance optimization (I think browsers now optimize when converting JS to bytecode.
Refer to MDN resource on for-loops for more information; here's a snippet:
for ([initialization]; [condition]; [final-expression])
statement
initialization
An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.
The result of this expression is discarded.
condition
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.
final-expression
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
statement
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements. To execute no statement within the loop, use an empty statement (;).

Iterating a for loop outside of the initial conditions

For instance let's say I have the normal loop:
for(var i = 0; i < 25; i++)
{
//code executes here
}
Notice the i++ I know it iterates the loop however, I am wonder if I can iterate elsewhere in the loop. Like so:
for(var i = 0; i < 25)
{
//code executes here
i++;
}
I attempted to implement it but it did not work. Is it possible to do it in this way?
There has to be a third expression in the for loop header, but it doesn't have to do anything and can in fact be empty. All you need is the semicolon.
for(var i = 0; i < 25; )
{
//code executes here
i++; // increments "outside of initial conditions"
}
Note that the for loop construct exists in the form it does because that's a very common pattern, and sticking to it whenever possible is a good idea to avoid unpleasant mistakes. For example, it means that you have to be careful with continue statements in the body of the loop:
for (var i = 0; i < 25; ) {
// code ...
if (whatever)
continue;
// code ...
i++;
}
The continue statement in a for loop does evaluate the third header expression, but it will skip the expression inside the loop body.
You can use any combination of statements for C-style "for" loops.
Initializer
The first statement is the initializer. This can be blank.
for (var i = 0; ...) // initializing in loop
for (; ...) // initializing outside of loop
Break Condition
The next statement is the condition: this typically cannot be blank unless you have a break statement in the loop, otherwise the for loop will become infinite. This is the greatest difference between "for" loops and "while" loops, so don't omit it.
for (;;) {
break;
}
Incrementor
The final statement is the incrementor. This increments the value so the break condition can trigger. You can easily omit this as well, as long as all branches of the loop will increment the value.
for (var i = 0; i < 25;) {
i++; // here's our incrementor
}
Why C-Style Loops Have Conditions Inside the Loop
Decomposing the full C-style for loop into each of it's pieces does the following:
var i = 0;
for(;;) {
if(i < 25) {
// your normal code would go here
i++;
}
else {
break;
}
}
There are many good reasons this is condensed into a single block within the "for" loop: writing code like this is verbose, prone to bugs, and makes it easy to create infinite loops by accident (crashing your program or exhausting a CPU until the program is quit).
Why Your Example Fails
You need to explicitly state you have a blank statement with at least 2 semicolons (3 statements) inside the loop. Otherwise, the code cannot be interpreted. The following line only has 2 semicolons:
for(var i = 0; i < 25)
The correct line is the following:
for(var i = 0; i < 25;)
Abstracting
Decomposing for loops to either change the break condition or the incrementor is bad form. Don't do it. However, if you must, this is probably a case of wanting to use a "while" loop. Typically, you wish to turn all of your suitable "while" loops into "for" loops, but there are rare exceptions. Just be warned: this easily leads to infinite loops, using up resources until you end the interpretor. "For" loops protect you from this.
You might be interested in break and continue statements. They give you more control over your loop.
//test if prime
var testInt = 42
for(int i = -10; i < testInt; i++) {
if(i<2) continue;
if(testInt%i==0) break;
}
Just make sure that no continue is called without previously changing the value of your variable. Otherwise an infinite loop is created.
An infinite loop in javascript is very bad. It freezes the browers and debugger, which means it is nasty to debug.

How strict is the syntax of a for-loop

So I have a fairly good amount of experience in coding. I've dabbled in Basic, HTML, Javascript, C, and C++, though the ones I've been using most recently are HTML and Javascript.
I am incredibly familiar with the for-loop. I've used it many times to loop through arrays, to operate recursive functions, etc. I know what it does and how to use it, but my question is about how it works.
Premise
In most languages, the basic syntax of a for loop is such:
var upperLimit = 10;
for(var i = 0; i < upperLimit; i++) {
/*Code to be executed*/
console.log(i);
}
In Javascript, this will output the numbers from 0 to 9 in the console.
I know that the parentheses contains 3 parts, each separated by semicolons.
The first is the initialization, which typically sets up the variables to be used to loop the statements.
The second is the condition, which runs before any of the code between the curly braces is executed. If it results in a True, the code is executed. Otherwise, the for-loop stops.
The third is the increment, which contains the last bit of code to be executed in the loop, and, by extension, the last thing executed before the next condition check.
Question
So, again, my question is how strict are these definitions?
The initialization's definition doesn't allow for much. It just says that that line is executed once, it's executed before anything else in the loop, and it's scope is limited to the loop. I can't think of much else you'd want to put in that position other than an iterative variable.
But what about the other two? I've seen codes where the condition is simply a variable, and as long as it's positive (since positive numbers taken as a boolean just covert to true), the loop continues.
Then there's the increment, which seems to be the loosest of these parts. Is it really just the last thing to be executed in a code, or does it explicitly need to iterate the variable declared in the initialization? It seems to be the former for the languages I'm familiar with.
For example, I decided to make a non-standard for-loop, and I came up with this routine:
var numbers = [0,1,2,3,4,5,6,7,8,9];
for(var i = 0;
numbers.length;
console.log(numbers.pop())) {}
It runs exactly as I expected: It outputs each member of the numbers array in the console in descending order, leaving an empty numbers array afterwards, and it's done using what is basically an empty for-loop.
Ending
So are my assumptions correct? If so, are there any practical applications for using a for-loop in a format apart from the one I wrote at the top of this question (possibly closer to he second format)?
Before all, you give a array
var numbers = [0,1,2,3,4,5,6,7,8,9];
The codes below is a correct for loop.
for(var i = 0;
numbers.length;
console.log(numbers.pop())) {}
Javascript defined for like this
for ([initialization]; [condition]; [final-expression])
statement
For you code initialization is 'var i = 0', and execute once at start of loop.
The condition is 'numbers.length', and value is 10. When a number not 0, Javascript will convert it to boolean true. So condition is true.
The final-expression is 'console.log(numbers.pop())'. When execute 'numbers.pop()', numbers.length change to 9. But it still is true.
At second time, condition will return true again. The final-expression is execute too.
Until numbers.length become 0, Javascript convert it to boolean false. The loop will end.
The scope of the initialized variable is not limited to the loop, it's valid for the whole function (undefined before that line). You can initialize multiple variables using a comma. for (var i=0, j=1; i < 10; i++)
The second part, anything that evaluates to a truthy value will cause the loop to keep going:
Truthy: 1, -1, true, "something", {a: 2}
Falsey: 0, false, null, undefined
You could omit this and rely on a break in your code
The third part just lets you update the looping variable, you could omit it and do it within the for loop body.
Here's an answer that provides a nice way to loop that is non-standard, and comes with caveats, please see the link.
var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];
for (var i=0, item; item = list[i]; i++) {
// Look no need to do list[i] in the body of the loop
console.log("Looping: index ", i, "item" + item);
}
In most languages, the basic syntax of a for loop is such:
for(initialization; condition; iteration) {
/*Code to be executed*/
}
Both three are usual expressions and you can use any valid expressions here:
for(
var i=arr.length, othercond=true;
i;
othercond?i--:i++, console.log(i),updateothercond()
);

FizzBuzz in Javascript: the code won't execute or print at all

Have been playing around with the FizzBuzz problem, and I am wondering why the following code won't execute, nothing gets printed to the console.
var i = 0;
while (i = 0, i < 100, i++ ) {
if ( i % 3 === 0) {
console.log("Fizz");
} else if ( i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
What am I missing?
You used the wrong looping construct. It should be a for, not while. Also note that it's semicolons between the clauses, not commas:
for (i=0; i < 100; i++) {
What you have is this:
while (i = 0, i < 100, i++) {
The comma just evaluates the left side, throws the result away, and then evaluates the right side. So that sets i to 0 (and discards the zero value returned by the assignment), tests that i is less than 100 (but does nothing with the true value returned by the comparison), and uses the value of the last expression (i++) as the loop condition for the while. Since i is 0, which is falsy, the loop body never executes.
Note that if you had used ++i instead, it would make no difference in the for case, but your while version would loop forever instead of not running at all, since i would already have been incremented to 1 the first time it was tested for truthiness.
I believe you are simply confusing the way you make 'for' and 'while' loops. You've built your 'while' like you would a 'for'!
Think of it this way: when you write a while loop like this:
while(i<100) {
You're saying, while (this condition is true). All that you need between the parentheses is a statement to determine whether it's true or not. Somewhere in the loop, you (usually) would need to change the value of i, or you'd (probably) get an infinite loop.
Now, the for loop, we'll need more information between the parenthesis... we'll need all the information that determines the amount of loops we'll take. Just like you've written it there, we're writing for (when my variable equals this; Loop until this condition is true; change the variable like this).
Generally, this means that 'while' provides more flexibility in how you determine the logic of your loop, but a 'for' loop is probably the easiest to read.

Why is my Do While loop returning undefined?

I'm currently learning javascript and I'm a little confused on why my do-while loop isn't working. Maybe I'm missing a core concept of how it's supposed to work, but I just don't seem to get why this isn't working. I could use a for loop or regular while loop to iterate through this list, and I understand those fine, but I'd like to figure it out using a do-while loop. Can anyone explain what is wrong?
i=0
var names = ['Bobby', 'Chris', 'John', 'Joe'];
do{
i+=1
}
while(i < 4){
console.log(names[i]);
}
The syntax should be with everything between the do and while braces:
do{
console.log(names[i]);
i+=1
} while(i < 4);
(Fiddle)
Your syntax is wrong, when you're using do{ }while() the while part doesn't take any braces, there's no need to.
Think of Do..while blocks as "Shoot first, ask later"
In other words, you execute a block of code first, and then you figure out if the condition is still true.
The reason you're getting an undefined output is because you're trying to access an undefined element.
JavaScript arrays are zero based, it means that if you have an array with 4 elements you're going to have indices going from 0 to 3
Because of the nature of do{ } while() you're incrementing your i BEFORE testing whether or not you've reached the end of the array, therefore when your loop ends, your i has the value of 4
and you're asking javascript for the value of names[4] which doesn't exist, and you end up with an undefined console output.
How to fix this?
It depends on what you're trying to achieve. Your code seems to me like you're trying to access the last element on your array, if that's what you're trying to do change your current condition form:
while(i < 4) to while(i < 3) and your code will work
Don't take my word for it, here's a fiddle for you:
http://jsfiddle.net/n8exp/

Categories