Basic While loop query - why is "1" logged? - javascript

Why does this while loop print "1" at the end?..I only want it to print console.log statement. Saw when using Codecademy.
for (i = 0; i < 2; i++) {
console.log("I understand for loops twice..lol");
};
var whileUnderstand = 0;
while(whileUnderstand < 2) {
console.log("I understand while loops twice..lol");
whileUnderstand++;
}
That question doesn't have the direct answers to the question that i asked. Furthermore, it only includes console.log statements instead of loops. Mainly, there are no answers saying that "The console is simply outputting the last evaluated value of the statement." which is the answer that solved my question.

This will only happen when running the code in a browser console.
It's caused by this line:
whileUnderstand++;
The console is simply outputting the last evaluated value of the statement.
The reason only 1 is logged and not also 0 is that outside of a console.log() call, only the last statement is logged.
For example if I have the following code snippet only "d" is logged:
var a = "a";
var b = "b";
a = "c";
b = "d";

var whileUnderstand= 0;
while(whileUnderstand<2) {
console.log("I understand while loops twice..lol");
whileUnderstand++;
}
Because it doesn't increment whileUnderstand when its equal to 2 if you want to print 2, you need to do this
var whileUnderstand= 0;
while(whileUnderstand<3) {
console.log("I understand while loops twice..lol");
whileUnderstand++;
}

Related

JS array being overwritten by bolean values when being read

First time around here, and I'm an awful dev, so forgive in advance my possibly numerous mistakes :)
here's my issue: I'm trying to make a program that checks the proportions of each number from 1 to 9 in an array (I'm putting Benford's Law to the test), for that I have created 9 different variables (basically nX where X=1-9), I'm reading through my array with a for loop, and incrementing on each of my variables every time that the corresponding number is found (if array[i]= X, nX++), and I then console log my array. The issue is that on that console log, all values in my array are set to "1", which isn't the case prior to the execution of these few lines. So I'm not quite sure what happens, but I'm guessing that my "if" checks are returning "true" and changing the value of my array elements to 1 to reflect that.
So my question would be: any of you wise wizards know what I'm doing wrong and how to keep my data from being corrupted by this operation?
here's some code:
for (i = 0; i < benfordArrayProcessed.length; i++) {
if (benfordArrayProcessed[i] = 1) {
n1++;
} else if (benfordArrayProcessed[i] = 2) {
n2++;
} else if (benfordArrayProcessed[i] = 3) {
n3++;
}
[...]
In your expression, you need use boolean expression instead of assignment, e.g. if (benfordArrayProcessed[i] == 1). The values in the error get overwritten with because of assignment int he first statement itself and that's the reason you see 1 for all the elements.
Apart from the == usage, you can also chose to go for a switch statement:
for (i = 0; i < benfordArrayProcessed.length; i++) {
switch (benfordArrayProcessed[i]) {
case 1:
n1++;
break;
case 2:
n2++;
break;
case 3:
n3++;
break;
[...]
}
}
Or, use an object with keys to up the numbers (a bit more tricky and depending on how you want to implement the rest of your code):
const n = {
1: 0,
2: 0,
3: 0,
};
for (i = 0; i < benfordArrayProcessed.length; i++) {
const num = benfordArrayProcessed[i];
n[num]++;
}

Is there an alternative to console.log() which lets you print out and update a single line instead of spamming the console?

I am looking for a way to print out a given variable f.ex. the i of a for-loop for each iteration, without it resulting in the entire console being filled with new lines of new values. Is there a console. method for just printing one line, and updating that as we go?
I realise that you could do this by implementing a text-field in your program which you change the with each iteration, but if there is a way of doing this in the console it would be a bit easier (and perhaps quicker? although I am really not sure about that). Thanks in advance.
If there is still confusion about what im asking, what i want is my console to print out:
"i = " i once, and then update the i in that one line, instead of:
i=1
i=2
i=3
1=4
.
.
.
which gets really messy as you go. For the exact example of the i in a for loop, you could get this value from just console.log()'ing the same thing for each iteration, and a number will pop up beside it (in firefox anyway), but i would like to be able to do this with some more useful information.
Option 1: use console.groupCollapsed() and console.groupEnd():
console.groupCollapsed();
for (let i = 0; i < 100; i+= 1) { console.log(`i = ${i}`) }
console.groupEnd();
Option 2: set the values in an array or a string and log the var when the iterations finish:
let valuesToLog = [];
for (let i = 0; i < 100; i+= 1) { valuesToLog.push(`i = ${i}`) }
// see it as an array
console.log(valuesToLog);
// see it as a string, with each value separated by ', '
console.log(valuesToLog.join(', '));
how about JQuery console.clear()?
$(function(){
loop_counter();
});
function loop_counter() {
for (let i = 1; i <= 100; i++){
console.clear();
console.log ("i=", i)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

JavaScript: setInterval and for loop explanation

i searched around for a couple of questions related to the use of the for loop and the setInterval function in JavaScript but i couldn´t find a concrete answer on why this snippet doesn´t work. Could someone explain please what´s happening under the hood and why this code doesn´t print anything at all?
for (let i = 0; i++; i < 10) {
window.setInterval(function () {
console.log('Test');
} , 100)
}
Your for loop is not correct. The condition needs to be the second statement in the for loop.
Following code should work.
for (let i = 0; i < 10 ; i++; ) {
window.setInterval(function () {
console.log('Test');
} , 100)
}
Expected Syntax for loop. You can read more here
for ([initialization]; [condition]; [final-expression])
statement
EDIT 1:
Though all answers (including mine) mentioned that condition needs to be second statement in the for loop which is correct. There is one more additional important behavior.
The for loop for (let i = 0; i++; i < 10) is actually correct in terms of grammar and even the javascript runtime executes this code.
But, as in your case, if the condition is evaluating to falsy value then it would exit the loop.
Breaking your for loop for (let i = 0; i++; i < 10) into each seperate construct
Initialization: let i = 0; This statement initializes the value of variable i to 0.
Condition: i++; Javascript evaluates the statement to check if the statement is true or not. In case of i++ the runtime firstly checks for the current value of i which is 0 . Since 0 is considered a falsy value the condition evaluates to false and hence the statement is not executed. Also, i++ statement is a post increment which basically increments i and then result the original value of i.
So, if you would have written loop like below, using the intiliaztion of i=1, then it would have worked, though it would be running infinitely untill the browser/Server crashes as the condition i++ would always evaluate to true. I hope that makes sense.
for (let i = 1; i++; i < 10) {
// Statements would run
}
Or
for (let i = 0; ++i; i < 10) { **// Pre increment**
// Statements would run
}
Or
for (let i = 0; i=i+1; i < 10) { **// increment i by assigment
// Statements would run
}
Douglas Crockford in his book Good Parts mention about the usage of ++ & -- and how it can confuse readers.
your for loop syntax is wrong, should be
for (let i = 0; i < 10; i++)
your setInterval code will run every 100 milliseconds for each iteration of the loop (so 10 times every 100 milliseconds)
Nothing to do with setInterval, you simply malformed your for loop:
This:
for (let i = 0; i++; i < 10)
Should be this:
for (let i = 0; i < 10; i++)
First declare the initial state of the loop, then the terminating state of the loop, then the incremental change of the loop.
Observe.

Extra output from Javascript nested loop

while practicing loop in JS, I wrote following code.
var bool = true;
while(bool) {
for (var i = 3; i >= 0; i--)
{
console.log(i);
bool = i;
}
}
The output I expected was:
3
2
1
0
(1 digit per line)
The output I encounter was:
3
2
1
0
0
(1 digit per line)
My question is - how does the code or environment component produce the extra "0"?
Thank you for your time and help.
The observed result is produced in Chrome (F12 -> console tab)
screen shoot from chrome
Also, on code academy's practice setting.
And somehow I cannot produce /or observe any result from the "Run code snippet".
UPDATE:
By switching
console.log(i);
and
bool = i;
I got 3 2 1 0 instead.
This would confirm Pointy's answer - no expression, only function call - Thanks again!
The last 0 is just the console mechanism telling you the value of the last expression statement evaluated. If you change it:
var bool = true;
while(bool) {
for (var i = 3; i >= 0; i--)
{
console.log(i);
bool = i;
}
}
"hello world";
you'll see hello world instead of the last 0.

For Loop Behaviour

This question is regarding Javascript for loops, where I've been having some weird behaviour.
My For loop currently looks like this:
var UnitAmount = 2;//(value verified, yet not declared like this)
var DamageAmount = [1,3];//(value verified, yet not declared like this)
function forcerefresh () {
for( i=0 ; i < UnitAmount ; i++ ) {
//(10 lines of Stuff)
var check = 0;
for (c = 0; c < DamageAmount[i] ; c++ ) {
debug[0] = damage[i][c].getElementsByClassName("writedamage")[0];
debug[1] = damage[i][c];
debug[2] = unit[i];
check = check + 1;
console.info("Unit:",i,"Loop:",c,"Debug:",debug,"Check:",check, "Race:",unitrace[i], unit[i].dataset.race);
alert("Debug:"+ debug );
damageCalc(damage[i][c].getElementsByClassName("writedamage")[0],damage[i][c],unit[i]);
}
}
}
In here, debug, alert, Check and the console write call are already added to attempt to find the problem - I'm getting an infinite loop here.
The output im getting in the console shows that while the i constant walks as intended, but the c Iteration count starts at 0, jumps to 2, and then stays 2 - and since the DamageAmount[1] = 3, this creates an infinite loop. And where the c might stick at value 2, the check values does walk up through the iterations.
As for the amount of variables involved, I've checked time and again with the console, and all of them are defined, and the values I expected. The Code is located at http://age-of-wonders-3.wikia.com/wiki/MediaWiki:Units.js, but if any parts are requested I'll of course post them here.
Any help is appreciated!
Try using for of or .forEach on an array

Categories

Resources