Variable Assignment in basic 1-10 counter - javascript

Here is a very basic counter to 10:
for (var i = 1; i <= 10; i++) {
console.log (i); // outputs 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
}
console.log(i);
I would expect the value of i in global space to be 10. It is 11. The only reason I can think of is that it is assigned 11 to break the loop i <= 10.
Is that the correct reason?

Yes, for loops work in this fashion:
for (/*initial conditions set at beginning of loop*/;
/*break condition checked before entering the loop each time*/;
/*command to execute at the end of each loop*/)
{
// stuff to do during loop
}
So your assumption is correct, the for loop runs until i = 11 because that is the first time the loop has reached the break condition.
For loops were created to avoid repetitive while or do/while loops. The above loop can be thought of as:
/*initial conditions set at beginning of loop*/
while (/*break condition checked before entering the loop each time*/){
// stuff to do during loop
/*command to execute at the end of each loop*/
}

A for loop of the form:
for (<inits>; <tests>; <repeats>) {
<body>;
}
is equivalent to:
<inits>;
while (<tests>) {
<body>;
<repeats>;
}
On the last iteration of the loop, i++ will be executed to set i to 11. Then when it returns to the top of the loop, the test i <= 10 will be executed. Since this is false, the loop terminates. At this point, i is still 11.

Related

while loop to print out only odd numbers in javascript

let number = 0;
while (true) {
if (number%2 === 0) continue;
console.log(number);
number ++;
}
I wanted to infinite loop to print out only odd numbers. But this doesn't seem to work. What am I doing wrong?
Let's have a brief understanding of the code execution.
When the following code is executed...:
let number = 0;
while (true) {
if (number%2 === 0) continue;
console.log(number);
number ++;
}
...the following happens:
The first line allocates memory for a variable named number and stores a value of 0.
The while loop starts, and it checks whether the condition is true, and yes it is, and always will be, as the condition is simply true.
Then, it checks whether the number mod 2 returns 0, and definitely, it does, since 0รท2 is 0 and the remainder is 0, so the condition inside the if statement is true, and therefore it executes the code correspondingly. When it sees continue, it jumps back to step 2 and checks the while loop condition, then comes back here, then goes back to step 2, then again comes back here and this never ends(ends when you stop the code execution or close your browser obviously).
Simply put, it never goes forward to the console.log and the number++ line. This is why your code isn't working.
The code from others work because the control actually moves forward in the code and never actually becomes stuck in the above loop.
Try this code
let number = 0;
while (true) {
if (number % 2 != 0)
console.log(number);
number ++;
}
The code you're using will not work because you defined number=0 and then you're checking the condition if(number%2==0) continue; so this condition will always return true because the number is defined 0 and the number++ will never increase.
let number = 0;
while (true){
if (++number % 2 == 1){
console.log(number);
}
}
no need a continue statement, just check the remainder is 1 the print the value in the loop.
you can further shorten the if condition as if (++number % 2)
You should increment the number when it is even also, to check the next number and so on:
let number = 0;
while (true) {
if (number%2 === 0){
number++;
continue;
}
console.log(number);
number ++;
}
Whatever number is, increment it first. Otherwise, when it is even, it never reaches to number++ any more.
let number = 0;
while (true) {
number ++;
if (number%2 === 0) continue;
console.log(number);
}

Strange behaviour of for loops

Can anyone tell me why for loop increments even on failed iteration?
for (var n = 0; n <3; n++) {
alert(n); // displays 0 , 1 , 2
}
alert(n); // gives 3
But shouldn't it be like
if(condition):
//desired stuff
increment;
else:
exit;
I seldom use iteration variable mostly I just throw them away upon loop completion but in this case found it to be the cause of a bug
Conceptually n++ is called just after the final statement of the loop body, and the stopping condition is evaluated just before the first statement of the loop body.
So your code is equivalent to
for (var n = 0; n < 3; ) {
alert(n);
n++;
}
Viewed this way, the reason why n is 3 once the loop exists ought to be obvious.
Note that in javascript, n leaks out of the for loop.
for (var n = 0; n <3; n++) {
alert(n);
}
alert(n);
Working of for loop is as follows -
First it initialize the n to 0;
Then it checks the condition whether it is true or not in this case condition is n<3.
Finally it increments the n and again check the condition and if it is true,It again goes in for block. And if the condition is false, It exit the for loop.
In your code when n=3 condition get false. So final value of n is 3.
Just executed the code at chrome console:
It works as expected.
As you have commented that n will be alert with 3, it is wrong, because when n will be 2, condition will be checked i.e. 2<2 will be wrong, then it will be jump from the loop and will alert 2 not 3.

loop flowing steps

This function come from the book "Eloquent Javascript", chapter 3, function.
I don't understand the flowing of the script.
Here is a "for loop" with an impossible mission to make a count value that is equal to 0 and smaller than 0.
At the beginning I expected that it would stop the program but the program is smart. why the impossibility to run the loop doesn't stop the program?
Here is the snippet:
var power = function (base, exponent) {
var result = 1;
for(var count = 0; count < exponent; count ++) {
//repeat as many as needed the self multiplication.
console.log("count = ", count);
result *= base;
console.log(result);
}
return result;
};
console.log("finally we get the number ", power(2, 0));
/* A little question with exponent = 0
Why is that not an error. It is impossible to initiate
with count = 0 && count < exponent.
Weird.*/
The output in repl.it
Native Browser JavaScript
finally we get the number 1
Because count < exponent or rather 0 < 0 is false, so the loop doesn't run and it returns the value of result when it was defined as 1:
var result = 1;
for(var count = 0; false; count ++) {
// This doesn't run
}
return result; // So it's still 1
Thanks to fuyushimoya, I understand:
The first statement in the parenthesis is the initialization of the variable. It is atated anyways before the loop begin. The second statements is a condition, evaluated before the loop is executed, if this statement boolean value is true, the statement inside the loop is executed. after each loop iteration. It change the variable value and then this new value is tested by the second statement and eventually the loop iterates again.
In a case in which the second statement is false at the beginning, the loop doesn't run and the situation is as if we have the first statement alone. See the documentation.

Pre-decrement operator in JavaScript while loop causes stack overflow

Recently I was going through some JavaScript code and at multiple places they are using a while loop to iterate over arrays. The way they do it is as
var i = dataArray.length;
while ( i-- ) {
// iterating over the array.
}
We know that the post-decrement operator here would first supply the value to while call and then will reduce it by one. So in this case for the first iteration if the array length is 10, the while call checks for i to be 10 and we get the value of i inside the loop to be 9. This continues till i reaches a value of 0 and then we exit out of loop. Precisely speaking we are iterating the array in a reverse manner.
This is fine. Where it really confuses me is when I write a pre-decrement operator, the while loop runs forever resulting in a stack overflow.
var i = dataArray.length;
while ( --i ){
// This loop would run forever.
}
Why is this happening? Won't doing --i will also result into i hitting the 0 value at some point of time and breaking the loop?
This is only the case if dataArray is empty. In that casen i = dataArray.length becomes zero. Then when you enter the while loop, i is pre-decremented to -1. Since all non-zero numbers evaluate to true, the loop keeps on going forever.
However, if the array has any elements, this will not happend and the loop will terminate. This code will illustrate the effect without craching anything:
function loop(x) {
var i = x.length;
while ( --i ) {
console.log(i);
if(i == -5) break; //Break after a while so we avoid an endless loop.
}
}
loop([]);
loop([1,1,1]);
The output of the first call is -1, -2, -3, -4, -5, and the output of the second call is 2, 1.
JSFiddle.
Ideal way of writing While loop.
while(condition){
// Your code
// iterator update (i++/i--)
}
Why you loop stops? JavaScript considers 0 as false and stops when reaches 0.
Also can't tell why predecrement runs forever. This might be because i never reaches 0;
Loop simulation
var data = [];
function createArray(){
for (var i=0; i<10; i++){
data.push(i);
}
}
function preDecrementLoop(){
var i = data.length;
while(--i){
console.log(i);
}
}
function postDecrementLoop(){
var i = data.length;
while(i--){
console.log(i);
}
}
(function(){
createArray();
console.log("pre decrement");
preDecrementLoop();
console.log("post decrement");
postDecrementLoop();
})()
Note: --i will skip loop for 0 since 0 is considered as false, while (0) == while (false).

Nested Javascript for loops with break and label statements

I'm kinda new to Javascript and currently going over the book Professional Javascript for Web Developers and I came across this code which uses a break statement to exit the current loop and jump to a label named outermost.
Now I understand what break and labels do but I can't wrap my head around why the value ends up being 55 at the end?
Ok so the for loop with var i will loop 4 times then at 5 it breaks out to label:outermost and same with j so the first iteration i = 4 and j = 4 and num = 2. I guess this part confuses me.. at what point does the code stop. My first instinct if I were to code this from scratch is to have an outside variable and set the condition on that. But with the below code I don't get where the control structure lies and the final value. Appreciate any help or to be pointed in the right direction, thanks.
var num = 0;
outermost:
for (var i=0; i < 10; i++) {
for (var j=0; j < 10; j++) {
if (i == 5 && j == 5) {
break outermost;
}
num++;
}
}
alert(num);
This nested loop is emulating an odometer. i is the 10's digit, j is the 1's digit. Every time the 1's digit changes, num is incremented; at the start of each iteration, num contains the odometer's value.
The loop stops when both i and j are 5. At that point, the odometer would read 55, and that's what is in num.
When i was 0 to 4, the innermost loop is executed 50 times. When i = 5, the innermost loop is executed just 5 times until it reached i==5 && j==5 and jumped out. So it's total of 55 times.

Categories

Resources