I read about closures and find this code.
for(i=0;i<5;i++){
setTimeout(function(){
console.log(i);
},2000)
}
This outputs 5 number 5 times after 2 second. I understand this but before five appears there is number above him. And when I execute again this code it changes it adds 5 to his old value. What is it? Write code on console, see what it outputs then explain me what is it?
It's the "result" value of the evaluated statement, which for a loop is the result value of the last statement in the loop body, which is the return value of the setTimeout call. And that returns a timer id (which allows you to cancel the timeout).
You also can see this behaviour with more simple statements:
> 0;
< 0
> console.log(1);
1 // the output of the log()
< undefined
> var i=2;
< undefined // a declaration has no result
> var i=3; i;
< 3
> for (;i<3;i++) 4;
< undefined // the body was not evaluated
> for (;i<4;i++) 5;
< 5
Notice how the leading arrow represents input and result output.
That number is the intervalID
Code: when you run the below code in browser debugger
setTimeout(() => console.log('hello'), 2000);
Response would be like
> 1822
> hello
You can use that intervalID to remove clear the timeout
Just to show you the confirmation of that number as intervalID
> var test = setTimeout(() => console.log('hello'), 2000); test;
< 11272
hello
> console.log(test);
11272
< undefined
Related
I was playing with the break and continue keyword but I notice in chrome console this code doesn't work
for (let i = 0; i > 5; i++) {
console.log(i);
} //this will print all number from 1 to 5 but console showing undefined
However I tried changing i = 5 or i === 5 still it doesn't work
But when I changed it to i < 5 then it yields correct result.
Why is that?
your condition is i > 5. At the beginning i = 0 so it will not run ever.
put i < 5
Please check following diagram
Condition getting false on the first time so code block won't execute
i<5 indicates that the for loop will run as long as i is less than 5. i>5 indicates that 0 is less than 5 (let i = 0). So the correct program should be -
for (let i = 0; i <= 5; i++) {
console.log(i);
}
i wanted see what the output will be if the condition for executing the code block is i = num. when i run the code, vs code terminal just shows node (path of my file) and i subsequently cannot execute any code from any file again. i must restart vs code and change the condition to i < num. why is this so? running the code in the code snippet here also seemingly crashes the page.
is this an infinite loop? however i don't see how it is an infinite loop as the condition to run the code is i=num. if i =/= num, shouldn't an error be returned instead of crashing vs code?
function FirstFactorial(num) {
let solution = 1
for (let i = 1; i = num; i++){
solution *= i
}
return solution;
}
console.log(FirstFactorial(5))
One thing to address. The second parameter for the for loop should be a condition.
i = num
is not a condition.
If you want to compare those variables you can use the triple ===
the issue is the i = num in your:
for (let i = 1; i = num; i++){
you want i <= num for the for loop to iterate.
for (let i = 1; i <= num; i++){
solution *= i
}
The for loop iterates while the second block i <= num evaluates to
true.
As soon as its false it will break out of the for loop,
as 1 != 5 (where num is 5 in your example) having i = num; as your second block evaluates to false right away and the for statement does not run.
I have an easy drill to print all the even numbers between 1-1000.
I want to set the condition in the line of the loop and not below it..
This is what I've tried:
for (let i = 1; i <= 1000 && i % 2 == 0 ; i++) {
document.write(i + " ");
// I dont want the condition here !!!
}
I searched the forum and tried this too:
for (let i = 1;( (i <= 1000) && (i % 2 == 0) ); i++) {
document.write(i + " ");
}
It looks like the same code I think, but there is nothing in the console when I run the code..
The test condition in the loop header determines whether the loop will continue to iterate. Because the first value of i is 1, and 1 is not even, the loop body is never run.
The whole test expression must be true (well, "truthy") for the loop not to stop. Therefore, you cannot place the evenness test in the loop header. It must be a separate test inside the loop body.
Now, you could do this without a test by starting the iteration at 2 instead of 1 and adding 2 on each iteration. Then you don't need to test for evenness at all:
for (let i = 2; i <= 1000; i += 2)
document.write(i);
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.
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.