Im confused about JavaScript loop types.
for loop
I learned that this loop looping until condition isn't false. If it false on first try it will never run.
for (var i = 0; i < 9; i++) {
console.log(i);
}
while
It runs loop until condition isn't false. If it is false on first try, loop never starts.
var n = 8;
while (n < 9) {
n++;
console.log(n)
}
But i is 8 and n resulting into 9
questions:
In for loop is condition true even if i = 8 - 8 is less than 9 so loop should increase i at number 9.
Descricption of this two loops are pretty much the same whats the diference between them?
You see a difference because the last expression of a for loop runs after each iteration.
That means the following codes are equivalent:
for (var /* VariableDeclarationList */; /* Expression 1 */; /* Expression 2 */) {
/* StatementList */
}
var /* VariableDeclarationList */;
while (/* Expression 1 */) {
/* StatementList */
/* Expression 2 */
}
But when transforming to a while loop, you placed the expression n++ before the statements.
https://www.codecademy.com/en/forum_questions/510e3c1a3011b8fa25005255:
For Loops allow you to run through the loop when you know how many
times you'd like it to run through the problem such as for (var i; i
< 10; i++); this will continually increase i untill that condition
returns false, any number can replace the 10 even a variable. but it
will quit once the condition is no longer being met. This is best used
again for loops that you know how when they should stop.
While Loops allow you a little more flexability in what you put in it,
and when it will stop such as while ( i < 10) you can also substitue
in a boolean(true/false) for 10 as well as many other types of
varibles.
The key difference between the two is organization between them, if
you were going to increase to 10 it'd be a lot cleaner and more
readable to use a for statement, but on the other hand if you were to
use an existing variable in your program in your loop parameters it'd
be cleaner to just wright a while loop. In the For loop you MUST
create a new variable, thats not true for the While loop.
Related
I would ask my instructor, but whenever I do, he gives me an even more vague answer to my questions, so I'm asking yall for help. We "learned" (i.e. watched videos) about for and while loops and I get it, I feel like I do, but whenever it comes to doing the assignments given, I feel like they don't make sense. Like back in math class in high school, they'd teach you about the problems, but then when it came time to do your homework, the problems were completely different from what you just learned about. For instance, it says the basic while loop structure is:
while(condition is true) {
//do something
}
But then in this assignment, it gives me:
// Another way to write a while loop is to have a boolean variable
// where the condition goes and then test every time if you need to
// change the boolean to false.
// Below we have a variable lessThan5 and it is set to true.
// Create a loop that tests if our variable 'j' is less than 5.
// If it is less than 5 then Increment it by 1. If it is not
// less than 5 then set our lessThan5 variable to be false.
let lessThan5 = true;
let j = 0;
while(lessThan5) {
}
We didn't learn anything about using boolean values in while loops and I feel like I'm meant to infer what to do, and what structure to use and I just have no idea. Aside from the fact I feel like the instructions to many of these questions are poorly worded, which only confuses me more!
So then there's this third one:
// Example of what the number game would look like:
// Couple things to note:
// Math is a built in object in javascript.
// Math.round() will round a decimal number to a whole number.
// Math.random() returns a decimal number between 0 to 1.
// (But not including 1)
function guessNumberGame(guess) {
let guessing = true;
let number = Math.round(Math.random() * 100);
while(guessing) {
if(guess === number) {
guessing = false;
} else {
guess = Number(prompt("That number didn't work. Try again: "));
}
}
}
// Problem 3
// We will give you a number through the 'num' parameter
// Create a while loop that will loop 'num' amount of times.
// For example if num is 3 then your while loop should loop 3 times
// If num is 20 then the loop should loop 20 times.
// Increment k every loop.
let k = 0;
function keepLooping(num) {
}
If this Problem 3 is meant to be related somehow to the number game example, I can't see it. I don't even know what it is I need to be asking. Does this make any sense to anyone? And nobody else is publicly asking questions about any of this, and it's making me feel stupid and like I am the only one too dumb to get what's going on. I was doing really well and ahead of schedule with all this until this point, but just none of this is making any sense to me.
Welcome to programming, JavaScript (JS), and StackOverflow (SO)!
Let's dive into this a little deeper. First, a quick JavaScript primer: in JavaScript, everything can be classified as either an expression or a statement. At a super high and not-technical level:
expression: something that produces a value
statement: an instruction to the computer
(For a much longer explanation, see here)
Often, statements have slots that can take expressions. Loops are a great example of that.
For example, 1 + 1 is an expression, since it produces the value 2. Even more simply, 1 on its own is also an expression, since it produces the value 1. while(/*some expression here*/) is a statement that has a slot for an expression. for(s1, e2, e3) is also a statement that has slots for statements and slots.
So, the while loop acts on an expression, and will continue to loop as long as the value returned by that expression is truthy. truthy and falsey is an interesting concept in JavaScript and can be a whole essay on it's own, but the tl;dr of it is that anything that == true is truthy, and anything that == false is falsey
So for your first question, 0 < 5 == true, while 5 < 5 == false. Thus, if you make the value of j be greater than or equal to 5, the loop will break.
let lessThan5 = true;
let j = 0;
while(lessThan5) {
// For each cycle of the loop, check if `j` is less than 5
if (j < 5) {
// If `j` is less than 5, increment it
j++; // This is equivalent to saying j = j + 1, or j += 1
} else {
// If `j` is not less than 5, set `lessThan5` to `false`
// Not when the loop goes to iterate again, `false == false`, and it stops
lessThan5 = false;
}
}
I think given the above you should be able to solve the third problem. Please let us know if you have trouble with it, show us what you try, and we'll be happy to help some more :)
Let's take a deep breath and relax. I'm a very senior developer and can't tell -- from your examples -- what's going on here. Maybe that's because your instructor is terrible, maybe it's because you've missed some context in your class, and so it's omitted from the question.
I can answer the two questions you've been given. Hopefully it'll be helpful.
First:
I do not know why your materials claim that a while loop might be written this way. I've completed the assignment, but it seems very odd. But if they want you to complete it, here's a solution.
// Another way to write a while loop is to have a boolean variable
// where the condition goes and then test every time if you need to
// change the boolean to false.
// Below we have a variable lessThan5 and it is set to true.
// Create a loop that tests if our variable 'j' is less than 5.
// If it is less than 5 then Increment it by 1. If it is not
// less than 5 then set our lessThan5 variable to be false.
let lessThan5 = true;
let j = 0;
while(lessThan5) {
if (j >= 5) {
lessThan5 = false;
} else {
j++;
}
}
Moving on to the second snippet, the second snippet does not, to me, appear to be related to guessNumberGame in any way.
And the solution to "Problem 3" seems useless to me. A loop that doesn't do anything is not useful in real life.
That said, the solution to "Problem 3" is as follows:
// Problem 3
// We will give you a number through the 'num' parameter
// Create a while loop that will loop 'num' amount of times.
// For example if num is 3 then your while loop should loop 3 times
// If num is 20 then the loop should loop 20 times.
// Increment k every loop.
let k = 0;
function keepLooping(num) {
while(k < num) {
k++;
}
}
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)
In JS I stumbled across a kind of for loop which is for(;;) that functions like a while(true) loop. What do the semicolons function in the brackets of this for loop?
for (statement 1; statement 2; statement 3) {
code block to be executed
}
Statement 1 is optional and is executed before the loop (the code block) starts.
var i = 0;
var length = 10
for (; i < length; i++) {
//The for loop run until i is less than length and you incerement i by 1 each time. javascript doesnt care what you do inside, it just check whether you have variable with name i and length
}
Statement 2 is again optional defines the condition for running the loop (the code block).
var i = 0;
var len = 100;
for (i = 5; ; i++) {
//Here you are just initializing i with 5 and increment it by 1 there is no break condition so this will lead to an infinite loop hence we should always have a break here somehwere.
}
Statement 3 is optional and is executed each time after the loop (the code block) has been executed.
var i = 0;
var length = 100;
for (; i < length; ) {
//Here you are just checking for i < length which is true. If you don't increment i or have an break it will turn into infinite loop
}
In nut shell when you have no conditions or initialization's it turns into an infinite loop.
Usually, a for loop header contains 3 parts:
for (var i = 0 ; i < 10 ; i++)
// ^^^^^^^^^ ^^^^^^ ^^^
You first initialise a variable, check the condition and if it is true, do whatever the loop body says, then increment i.
What you might not know is that any part of the for loop header can be omitted. If the first part is omitted then no variable is initialised. If the second part is omitted then there is no condition check. It will always assume the condition is true.
So for(;;) is basically an infinite loop because it omitted the condition part of the for loop header. Every time, the condition is true, so it continues on forever.
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again testing for a condition). After the condition becomes false, the for loop terminates.
The for loop consists of three parts:
for (INITIALIZATION; CONDITION; AFTERTHOUGHT)
{
}
If you omit these parts the whole will be evaluated as:
for(; true ;)
{ }
The initialization and after thought are just ignored.
First semi semicolon ends initialization statement.
Second semi semicolon ends condition check statement.
In your case both statement are empty (no initializing and checking nothing every loop).
Well I'm just going to take a guess.
Typically a for loop might be like this:
for (i = 0; i < 10; i++)
so basically
for (;;)
is well forever, because loop condition is always met.
What I can still add is:
reference to the source,
This conditional test is optional. If omitted, the condition always evaluates to true.
we can leave any of these three blocks in the loop for,
information that this behavior of the loop for is similar like in in C language and others with syntax inspired by C, such as C++, Java etc.,
a practical example of using such a loop:
let i = 1;
for (;;) {
if (i === 4) {
break;
}
console.log(i++);
}
I will also add that the statment block after the for loop is also optional (we only need to put the ; at the end). To show this, here's the next example: equivalent to the above code, but without the block statmant in the for loop:
for(var i = 1; i < 4; console.log(i++));
plz check the code below:
for(i=0; i-DIL; i++)//see the condition here i-DIL .Is this correct?
{
}
is the second condition above in for loop correct?if so ,what does that mean?
actual code is:
javascript:R=0;
x1=.1; y1=.05;
x2=.25; y2=.24;
x3=1.6; y3=.24;
x4=300; y4=200;
x5=300; y5=200;
DI=document.getElementsByTagName("img");
DIL=DI.length;
function A(){for(i=0; i-DIL; i++)//see the condition here i-DIL .Is this correct?
{
DIS=DI[ i ].style;
DIS.position='absolute';
DIS.left=(Math.sin(R*x1+i*x2+x3)*x4+x5)+"px";
DIS.top=(Math.cos(R*y1+i*y2+y3)*y4+y5)+"px"}
R++
}
setInterval('A()',5); void(0);
Also can anyone help me describing the reason for placing void(0) at the end of the script?
And U can see that repeatedly image position is set over and over .How can i overcome that
Whether or not it's "correct" depends on what exactly you want the for loop to do. However, it is valid code, and hinges on the fact that 0 in JavaScript is "falsey", while other numbers are "truthy".
Essentially, when i and DIL are equal, i - DIL equals 0, which for the purposes of the for loop condition is evaluated as false, and it stops iterating. Given that DIL is the length of a collection, it's an interesting (but technically valid) method of iterating over the entire collection.
It's equivalent to (though I'd say less readable than):
for(i=0; i < DIL; i++)
it means execute code below till i-DIL != 0. ie here in your code it will work till i reaches DIL.
A for loops usually takes:
for(variable definition; condition; increment) {}
So, you need a condition. However, because Javascripts has loose content types, you don't have to use a comparison for it to be true or false.
10 - 1 // = 9 equals true
10 - 9 // = 1 equals true
10 - 10 // = 0 equals false
"legit string" // equals true
NULL // equals false
However, I do suggest to make an actual comparison just to avoid nasty browsers to break your condition.
for(var i = 0; i - DIL > 0; i++) {}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Potentially dangerous code below, line 2
Repeat: POTENTIALLY DANGEROUS CODE BELOW
var history = "";
for (start = 3; start = 1000; start += 1){
if(start % 5 == 0 || start % 3 == 0)
history += start + " "; }
Okay, this is the tenth time I've put JavaScript code in that's frozen my browser. It's putting my computer in shock. Are these panic attacks going to destroy her heart? Where can I learn about all the crap that might break my computer as I continue to learn and practice JavaScript? I'm looking for an exhaustive list, only.
Your loop: for (start = 3; start = 1000; start += 1){
The second part of a for( ; ; ) loop is the condition test. The loop will continue until the second part evaluates to false. To not create an infinite loop, change your code to:
for (var start = 3; start < 1000; start += 1){
Note: start+=1 is equal to start++. If you want a compact code, you can replace +=1 by ++.
An overview of the three-part for-loop, for(initialise; condition; increment):
initialise - Create variables (allowed to be empty)
condition - The loop will stop once this expression evaluates to false
increment - This expression is executed at the end of the loop
Always check against infinite loops: Make sure that the condition is able to evaluate to false.
Commonly made mistakes:
A negative incremental expression in conjunction with a is-lower-than comparison:
i-- decreases the counter, so i<100 will always be true (unless the variable i is initialized at 100)
A positive incremental expression in conjunction with a is-higher-than comparison.
A non-incrementing expression: for(var i=0,j=0; i<100; j++) (i doesn't increase)
A condition which is always true (such as in your case)
You just have to learn and read about it properly. Your loop condition start = 1000 will always evaluate to true, that's why the loop never terminates (an assignment returns the value which was assigned and any other number than 0 is evaluates to true).
The MDN JavaScript Guide is a great resource for learning JavaScript. Particular for this situation:
A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. A for statement looks as follows:
for ([initialExpression]; [condition]; [incrementExpression])
statement
When a for loop executes, the following occurs:
The initializing expression initialExpression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.
The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates. If the condition expression is omitted entirely, the condition is assumed to be true.
The statement executes. To execute multiple statements, use a block statement ({ ... }) to group those statements.
The update expression incrementExpression, if there is one, executes, and control returns to step 2.
As the others said, it mostly comes down to try and error.... that is a good way of learning anyway.
your conditional statement start=1000 will always return true. You cant found such fool proof's list for this, you have to learn from these mistakes on your own.
Uh - what did you wanted here ?
for (start = 3; start = 1000; start += 1)
do you wanted this ? ( from 3 to 1000 )
for (start = 3; start <= 1000; start += 1)
in first case you will stuck on 1000