why output this result when I make break to label in iteration? - javascript

I'm a newbie of javascript, and I certainly coundn't understand this output when I learn for statement..
foo: for(var i=0; i<3; i++){
console.log(i);
if(i==1){
break foo;
}
}
and I get some print like this..
0
1
to be honest, I dont know what happend here, I think that may throw error here because too deep iteration may be caused..
I want to get this result actually
0
1
0
1
0
1
...
maybe it's a stupid question, but I indeed want to get answer.
could anybody help me..

for(var i=0; i<3; i++){
console.log(i);
if(i==1){
break foo;
}
}
You are running a for loop which is iterating from 0 to 3 (excluded).
in each iteration it print the value of i.
if value of i is 1 then it break from loop
first iteration: i=0; print 0 continue as 0 != 1
second iteration: i=1 print 1 break as 1 == 1
lean more about for loop

Your loop is trying to output i while it is less than 3 and increment it by one for every iteration.
the if (i == 1) statement is true in the second iteration so the break gets executed which "exits" the loop.

An infinite loop will do it.
var v = 0;
while (true) { // <-- this runs forever!
console.log(v);
v ^= 1;
}
or with a limit of 1000 loops
var v = 1000;
while (v) {
out(v % 2);
v--;
}
// just for dispaying the result
function out(s) {
var descriptionNode = document.createElement('div');
descriptionNode.innerHTML = s + '<br>';
document.getElementById('out').appendChild(descriptionNode);
}
<div id="out"></div>

Actually break statement is used to get out of the loop.
As we know earlier for loop loops execution until condition (here i<3) is true. if the condition gets false then it terminates ie., when the i is incremented to 3.
But, the if condition to be checked is i==1 so whenever i is incremented to 1 the for loop gets terminated by break statement.
Each time the incremented value of i is printed in the console of the browser as a log. until the termination.

Your code does:
print i
then break
it will print 0 1 and then break the loop.

Related

why infinite loop doesn't apply when iterating backwards with for loop

I am learning javascript and I have two questions hope you can help :)
I have two for loops iterating backwards
first example :
for (var i = 10; i--;) {
console.log(i, "backward");
}
// starts at 9 and stops at 0
// without breaking condition
second example :
for (var i = 10; i >= 0; i--) {
console.log(i, "backward");
}
// starts at 10 and stops at 0
// with breaking condition that i >= 0
why in the first example we don't need to set a breaking point for the loop ? like i > 0 ? is it because 0 is false anyway ? so when it reaches 0 it automatically breaks ? and it won't keep iterating like 0, -1, -2, -3, ....etc ?
why in the second example the iterating starts at 10 while in the first example it starts at 9 ?
thanks for your support :D
Cheers
i-- is the breaking point. A post-decrement expression subtracts 1 from the variable and returns the previous value. So when i is 0, the value of i-- is 0, which is falsey, and the loop stops.
Because in the first example we're decrementing i during the repeat condition, which runs before the body, so the first iteration already has it decremented to 9. In the second example we're decrementing i in the update expression, which runs after the body, so it still has the initial value 10 during the body of the first iteration.
To understand what a for loop is doing, expand it into the analogous while loop.
for(initialize; condition; update) {
body
}
is roughly equivalent to
initialize;
while (condition) {
body;
update;
}

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);

(Javascript) I don't understand how the counter and result variables interact with each other

let result = 1;
for (let counter = 0; counter < 10; counter = counter + 1)
{
result = result * 2;
}
console.log(result);
So this code finds the 10th power of 2, or 2^10, and it works fine. I just don't understand HOW it works, specifically how the result and counter variable interact with each other. If I remove the for statement the answer comes out to 2 which makes sense. But when I add the for statement back in it comes out to 1024, and this doesn't make sense to me because I don't understand how the counter and result interact with each other. Sorry if I sound redundant, I'm a noob and have no idea what I'm talking about.
EDIT: I understand now, thanks
Let try and understand your code.
let result = 1;
In above statement you declare a variable and initialize it to 1
for (let counter = 0; counter < 10; counter = counter + 1)
{
result = result * 2;
}
The above is a for loop. What is a for loop.
A for loop is an iteration that repeats until a specified condition
evaluates to false.
Below is the syntax of a for loop
for ([initialExpression]; [condition]; [incrementExpression])
{
statement(s)
}
So in your case the loop will keep executing the statements until the condition evaluates to false. Which in your case is counter < 10 that means as soon as the counter becomes 10 the condition evaluates to false. But till it becomes 10 it keeps executing the below statement.
result = result * 2;
The below statement logs the value of result when the loop has finished executing.
console.log(result); // 1024
So result and counter don't interact with each other. Counter helps decides the number of iterations/cycles of the for loop. And the result is incremented because of the statements being executed inside the loop.
Hope this helps :)
For more please refer MDN Docs

Closure in JavaScript from CoderSchool

I was doing some studying on CodeSchool. While watching a tutorial I was confused by an example. What they were trying to explain in the video was that closures created in loops won't bind until the last minute. The aim for this code was to take a name check for it in the array and return the name alone with its position(without the zero convention). Since closures don't bind till the last minute this code is returning z 5. I am confused why this code is returning a 5 and not a 4. The length of my array is 4 and the for loop stops before 4 because i < passengerArray.length which is the equivalent of i < 4 therefore the last index checked should be passengerArray[3] which means my (i+1) should be 4 in the end and not 5. I hope that makes sense. This has been bothering me all day.
function assignTorpedo(name, passengerArray)
{var torpedoassignment;
for(var i = 0; i < passengerArray.length; i++){
if(passengerArray[i] == name){
torpedoAssignment = function(){
console.log(name + " " + (i+1));
};
}
}
return torpedoAssignment;
}
var give = assignTorpedo("z",["z","a","b","c"]);
give();
The for loop ends when the test condition fails. Why does it fail? Because i is not less than 4; it's equal to 4. Thus, in the console.log() output you see 5.
Also, the statement
closures created in loops won't bind until the last minute.
is a strange way of describing how things work. As soon as the name is found in the array, the variable is assigned a reference to the constructed function. When assignTorpedo returns that value, the closure exists. In the closure, the value of the variable "i" is already 4.
The following statement increments i by 1 after each pass through the loop. So, after the fourth iteration i will be increased by one and tested against the condition again, and then it will fail.
var arr = ["z","a","b","c"];
for ( var i = 0; i < arr.length; i++ ) {
console.log( i );
}
console.log( i );
The For loop finishes when condition "i < passengerArray.length" being violated which i equals 4 at that time.
then console.log(name + " " + (4 + 1)));
Power Tip:
From one of my lecturers in uni,
"Think a "For" loop like a 'While' loop like this"
i = 0;
while (i < passengerArray.length)
{
...............
i++;
}

Unexpected infinite loop

This code runs for infinity, why?
function f(n){
i=0;
if (n==2){
while(i<2){
f(i);
i++;
}
}
}
if n!=2 the function should do nothing
and if n equals 2 the function calls f(0) and f(1) so it should stop after that
but you only get infinite loop when you run it.
any one could tell why?
edit: there is nothing outside the function.
and no need for better code.Just asking why.
You can fix it by changing
i=0;
to
var i=0;
Your i variable is global (or at least its scope is external to f, so it's shared by all calls of the function). When n is initially 2, you enter the loop and this loop always resets i to 0 just before the increment. The sequence you have is thus
i = 0 // start of f
// enters loop for the first time with f(0)
i = 0 // start of f
i = 1 // i++
i <2 so loop again
i = 0 // start of f
i = 1 // i++
i <2 so loop again
i = 0 // start of f
i = 1 // i++
i <2 so loop again
i = 0 // start of f
i = 1 // i++
i <2 so loop again
i = 0 // start of f
i = 1 // i++
...
i is global. Declare it with var instead to keep it local to each instance. Otherwise, it is constantly reset to 0, so your while loop never ends.
Because you got f(i) all the time with i = 0. So when you are doing a loop, you are going to do f(0) indefinitly ! (same for every i) Just put a var on your i to stop your loop
Can you try this, i=0 is global variable, reason for f(i) setting the value each and every time along with Global variable, so you need to use var i=0; for initialize the i every time.
function f(n){
var i=0;
if (n==2){
while(i<2){
f(i);
i++;
}
}
}
Every time f() is called, i is set back to 0. Since you didn't do var i = 0, that means that i is global! Every time f() is called, the same value of i is used.
When you call f(2), you start a while loop. Every time you call f(i), you are re-setting i to 0. So the while loop never ends.
You need to make i local:
function f(n){
var i=0;
if (n==2){
while(i<2){
f(i);
i++;
}
}
}
This way every time f() is called, it creates its own i variable.

Categories