Task: Reverse and array,
My Solution:
function printReverse(arr) {
for (var i = arr.length; i >= 0; i--) {
console.log(arr[i]);
}
}
printReverse([1,2,3,4]);
My solution is correct but I don't understand why do we have to set the conditon to be i >= 0 why can't we set it to be i === 0
That statement defines when the loop will continue executing, not when it will stop.
So, if you made the statement i === 0, the loop would never execute, because in the first iteration, the value of i would be the length of the array (which is only 0 when the array is empty).
As an aside, I believe your code actually has a small bug. i should start being set to arr.length - 1;; as is, in the first iteration of the loop, it is printing out 'undefined'.
According to MDN
for ([initialization]; [condition]; [final-expression])
statement
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.
The statement is only executed only if the condition is true so if you'd use i === 0 the content of your for would never be executed
in first iterate the length is 4 and in for condition you check is 0 === 4 and its false so loop is end , but when you check 4 >= 0 it's return true.
The condition in the for loop is the condition that keeps repeating the loop. Setting it to i === 0 wouldn't even enter the cycle, if your array length is not 0.
function printReverse(arr) {
for (var i = arr.length - 1; i >= 0; i--) {
console.log(arr[i]);
}
}
printReverse([1,2,3,4]);
You can't set i = 0 because it will cause the initial value of i to be zero therefore causing the loop to start from 0 which would be the first element in an array.
The reason why you have to set i = arr.length - 1 is so it can start counting from the last item in the array.
i-- tells the loop to continuously decrement the value of i until the condition i >= 0 is met.
I set i = arr.length - 1 i.e. length of the array minus one, so that it starts it count at exactly the last element in the array. In your case where you had to use i = arr.length, the first value of i will be undefined.
i >= 0, simply tells the loop to continue running until i is neither greater than zero nor equal to zero. At this point, the loop terminates.
Related
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 (;).
I know that in javascript a 1 evaluates as true, while a 0 evaluates as false.
My question is regarding the while loop in javascript, in the format as follows:
while (condition) {
code block to be executed
}
If I pass a single integer as a condition for the while loop, how does the code function? More specifically, here is the code I was working on before posting this question:
function chunkArrayInGroups(arr, size) {
var newArr = [];
while (arr.length) {
newArr.push(arr.splice(0,size));
}
return newArr;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2);
and it seems to be working perfectly fine, returning the newArr the way I need it to by dividing the original array (arr) the amount of times required (size) and pushing that to the newArr.
How does the condition arr.length evaluate? My assumption is that it evaluates as true as long as it is not zero, i.e. a nonzero number, despite it not being a comparison such as i < 2.
This exercise came from freeCodeCamp:
Chunky Monkey
Any number that is not 0 evaluates to true.
0 evaluates to false.
So, your code will run until arr.length is equal to 0 - it is the same as saying while (arr.length!=0)
if you're evaluating array's length property, it will be true until array is not empty ( length is not 0 ). When the array is empty ( length is 0) evaluation will return false.
Yes
Yes, you are absolutely right, it evaluates as true whilst arr has a length because arr.length is > 0 so is considered true. It is a neat feature of javascript however it is not that readable (as you have found) and can therefore be confusing to anyone not used to it. However if you are coding for yourself, this is a clever little function!
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.
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.
I am at a loss how best to approach for loops in JavaScript. Hopefully an understanding of for loops will help shed light on the other types of loops.
Sample code
for (var i=0; i < 10; i=i+1) {
document.write("This is number " + i);
}
My understanding is that when i has been initialized, it starts with the value of 0 which then evaluated against the condition < 10. If it is less than 10, it the executes the statement document.write("This is number + i); Once it has executed the preceding statement, only then does it increment the next value by 1.
Guides I have consulted:
http://www.functionx.com/javascript/Lesson11.htm
http://www.cs.brown.edu/courses/bridge/1998/res/javascript/javascript-tutorial.html#10.1
http://www.tizag.com/javascriptT/javascriptfor.php
Now the guide at http://www.functionx.com/javascript/Lesson11.htm seems to indicate otherwise i.e.
To execute this loop, the Start condition is checked. This is usually
the initial value where the counting should start. Next, the Condition
is tested; this test determines whether the loop should continue. If
the test renders a true result, then the Expression is used to modify
the loop and the Statement is executed. After the Statement has been
executed, the loop restarts.
The line that throws me is "If the test renders a true result, then the Expression is used to modify the loop and the Statement is executed". It seems to imply that because 0 is less than 10, increment expression is modified which would be 0 + 1 and THEN the statement, e.g. document.write is executed.
My problem
What is the correct way to interpret for loops? Is my own comprehension correct? Is the same comprehension applicable to other programming languages e.g. PHP, Perl, Python, etc?
Think of a for loop as the following
for(initializers; condition; postexec) {
execution
}
When the loop is first started the code var i = 0 is run. This initializes the variable that you will be testing for inside the loop
Next the loop evaluates the i < 10 expression. This returns a boolean value which will be true for the first 10 times it is run. While this expression keeps evaluating to true the code inside the loop is run.
document.write("This is number " + i);
Each time after this code is run the last part of the loop i++ is executed. This code in this example adds 1 to i after each execution.
After that code is executed the condition of the loop is check and steps 2 and 3 repeat until finally the condition is false in which case the loop is exited.
This the way loops work in the languages you mentioned.
Lets have a look at the corresponding section in the ECMAScript specification:
The production
IterationStatement : for ( var VariableDeclarationListNoIn ; Expressionopt ; Expressionopt) Statement
is evaluated as follows:
1. Evaluate VariableDeclarationListNoIn.
2. Let V = empty.
3. Repeat
a. If the first Expression is present, then
i. Let testExprRef be the result of evaluating the first Expression.
ii. If ToBoolean(GetValue(testExprRef)) is false,
return (normal, V, empty).
b. Let stmt be the result of evaluating Statement.
...
f. If the second Expression is present, then
i. Let incExprRef be the result of evaluating the second Expression.
ii. Call GetValue(incExprRef). (This value is not used.)
As you can see, in step 1, the variable assignment is evaluated. In step 3a, the condition is tested. In step 3b, the loop body is evaluated, and after that the third expression is evaluated in step 3f.
Therefore your understanding of the for loop is correct.
It is to assume that it works the same way in other languages, since the for loop is such a common statement in programming languages (note that Python does not have such a statement). But if you want to be absolutely certain, you better consult their specification as well.
Your quoted source is wrong, and we can prove it...
The basis of the for loop has four separate blocks which may be executed:
for(initialise; condition; finishediteration) { iteration }
Fortunately we can execute a function in each of these blocks. Therefore we can create four functions which log to the console when they execute like so:
var initialise = function () { console.log("initialising"); i=0; }
var condition = function () { console.log("conditioning"); return i<5; }
var finishediteration = function () { console.log("finished an iteration"); i++; }
var doingiteration = function () { console.log("doing iteration when `i` is equal", i); }
Then we can run the following, which places the above functions into each block:
for (initialise(); condition(); finishediteration()) {
doingiteration();
}
Kaboom. Works.
If you viewing this page using Safari on the Mac then you can AppleAlt + I and copy the above two snippets, in order, into the console and see the result.
EDIT, extra info....
Also... the finished iteration block is optional. For example:
for (var i=0; i<10;) {
console.log(i); i++;
};
does work.
The second reference is wrong. Your explanation is correct.
Another way to think about it, if this helps you:
var i = 0;
while (i < 10) {
document.write("This is number " + i);
i++;
}
This is for statement syntax:
for(initalize, condition, increment) {
Do_some_things();
}
initalize Will executed only one time when for begin then it execute Do_some_things(); statement, and while condition still true it will execute increment and then Do_some_things();. if co condition false, for would exit.
for (var i=0; i < 10; i=i+1) {
document.write("This is number " + i);
}
var i=0 will execute one time (initalize).
i < 10 condition was always checked after a loop.
i=i+1 will execute after check i < 10 and result is true.
Value of i is: 0, 1, 3, 4, 5, 6, 7, 8, 9 (10 times loop)