I am learning the do-while loop and am unable to understand why this loop is running infinitely.
var condition = true
var getToDaChoppa = function(){
do {
console.log("I'm the do loop");
} while(condition === true){
console.log("I'm the while loop");
condition = false;
};
};
getToDaChoppa();
You never set the condition variable to false INSIDE the loop, so it will never execute any of your code outside of the loop until this loop has completed (which will never happen given your current example). Make sure that you set the condition variable to false inside the loop:
do {
console.log("I'm the do loop");
if (some_condition_is_met) {
condition = false;
}
} while(condition === true);
Do/While works like this. So you never change the condition inside the loop.
do {
//code block to be executed
}
while (condition);
//Code after do/while
There is a do..while and there is a while..: there is no do..while.. statement.
JavaScript allows block statements independent of other flow-control/definition constructs. Due to lack-of-a-required statement semicolon this does not result in a syntax error (it would in Java).
Here is some additional clarification relating to the syntax; other answers cover the logical error.
do {
console.log("I'm the do loop");
} while(condition === true) // semicolons optional in JS (see ASI):
// 'do..while' statement ENDS HERE
{ // starts a block statement which has naught to do with 'do..while' above
// THERE IS NO WHILE LOOP HERE
console.log("I'm the while loop");
condition = false;
}; // useless semicolon which further leads to confusion
On the other hand, if the do.. was omitted it would have been parsed as "just" a while statement which would have terminated.
// Basic WHILE statement - no 'do..' code, so NOT parsed as a 'do..while'!
while(condition === true)
{ // this block is now part of the 'while' statement loop
console.log("I'm the while loop");
condition = false;
};
Related
If I have the following for loop
for (var i = 0; i < SomeArrayOfObject.length; i++) {
if (SomeArray[i].SomeValue === SomeCondition) {
var SomeVar = SomeArray[i].SomeProperty;
return SomeVar;
}
}
Does the return statement stop the function's execution?
Yes, functions always end whenever their control flow meets a return statement.
The following example demonstrates how return statements end a function’s execution.
function returnMe() {
for (var i = 0; i < 2; i++) {
if (i === 1) return i;
}
}
console.log(returnMe());
Notes: See this other answer about the special case of try–catch–finally and this answer about how the forEach callback has its own function scope, so it will not break out of the containing function.
In most cases (including this one), return will exit immediately. However, if the return is in a try block with an accompanying finally block, the finally always executes and can "override" the return in the try.
function foo() {
try {
for (var i = 0; i < 10; i++) {
if (i % 3 == 0) {
return i; // This executes once
}
}
} finally {
return 42; // But this still executes
}
}
console.log(foo()); // Prints 42
This code will exit the loop after the first iteration in a for of loop:
const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
if (iterator.name == 2) {
return;
}
console.log(iterator.name);// 1
}
the below code will jump on the condition and continue on a for of loop:
const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
if (iterator.name == 2) {
continue;
}
console.log(iterator.name); // 1 , 3
}
The return statement stops a loop only if it's inside the function (i.e. it terminates both the loop and the function). Otherwise, you will get this error:
Uncaught SyntaxError: Illegal return statement(…)
To terminate a loop you should use break.
Yes, once the return statement is executed, the entire function is exited at that very point.
Just imagine what would happen if it did not and continued looping, and executing that return statement each time? It would invalidate it's meaning of returning a value when you think about it.
The answer is yes, if you write return statement the controls goes back to to the caller method immediately.
With an exception of finally block, which gets executed after the return statement.
and finally can also override the value you have returned, if you return inside of finally block.
LINK: Try-catch-finally-return clarification
Return Statement definition as per:
Java Docs:
a return statement can be used to branch out of a control flow block
and exit the method
MSDN Documentation:
The return statement terminates the execution of a function and
returns control to the calling function. Execution resumes in the
calling function at the point immediately following the call.
Wikipedia:
A return statement causes execution to leave the current subroutine
and resume at the point in the code immediately after where the
subroutine was called, known as its return address. The return address
is saved, usually on the process's call stack, as part of the
operation of making the subroutine call. Return statements in many
languages allow a function to specify a return value to be passed back
to the code that called the function.
"return" does exit the function but if you want to return large sums of data, you can store it in an array and then return it instead of trying to returning each piece of data 1 by 1 in the loop.
I'm quite new to JavaScript and I was wondering if it is possible to make an if statement affect two separate parts of code. For example:
console.log(1);
console.log(2);
console.log(3);
The code above should print the numbers 1, 2, and then 3 in that order, but I want to add a test to it. If the test passes, all three commands should run, but if it fails only a 2 should be printed. I could add two if statements like this:
if (test()) {console.log(1)}
console.log(2);
if (test()) {console.log(3)}
My problem with this is the test() function is being run twice. Is there a way to only run the test once while preserving the order of the numbers? Sorry if there's an obvious answer and I'm just missing it.
(I should add that this is just an example of 3 events that have to happen in order, so I need an answer that would work not just for printing consecutive numbers but anything situation where you would want 3 things to happen in order.)
This is best done by storing the value in a variable that will handle the control flow execution (this variable is known as a flag). You can make it as simple as this:
let testResult = test();
if (testResult) {
console.log(1);
}
console.log(2);
if (testResult) {
console.log(3);
}
This will ensure that if testResult is false (i.e. test returns false or a falsy value) then you will only have 2 printed, but if test returns true or a truthy value, then 1, 2, 3 will all be printed.
If you only want a single if statement, then use if-else and print 2 in both of them:
let testResult = test();
if (testResult) {
console.log(1);
console.log(2);
console.log(3);
} else {
console.log(2);
}
(note you could eliminate the first line in the code block above and just use if (test()) since you only call test once, but I've kept it just so you can see it's usable in many situations).
You can try ternary operator!
(test()?(event1;event2;event3):(event2))
So another alternative is to use the flag into the function you can skip heavy calculations or something, the down side of this is if you whant to return null
var TheTestFlag = null;
let test = () => {
if(TheTestFlag === null){
console.log("Entered into heavy logic");
//...do some stuff
// don't return assigne to the flag
//for exaple if(a>b) TheTestFlag = false;
TheTestFlag = false;
}
//return the flag
return TheTestFlag;
};
if (test()) {
console.log(1);
}
console.log(2);
if (test()) {
console.log(3);
}
I'm new at javascript and am using tampermonkey for a website.
What i want to do is monitor a variable on a page and when said variable reaches a certain value, go to another page, do something, and then recheck the value of this variable.
My logic was to:
setInterval(function(){reloadPage1},10000);
var variable = someTextonThisPage;
if(someTextonthisPage meets condition)
{
go to Page2;
execute something on page 2;
setNewValueForVariable; //(or just go back to initial
//and get the new value from there)
}
Now my problem is when the if executes, it goes to page2 keeps looping the if call even if i set the variable to something false.
I tried doing something like:
function doThis()
{
if(condition)
return true;
else return false;
}
if(doThis())
{
goToPage2;
do stuff;
doThis();
}
I end up having the if statement go on and on, going to page 2 and my settimeouts to do something on that page never execute because of the next iteration of the 'if'.
What am i doing horribly wrong in my thought pattern?
Your doThis() function is right. Everything ok with it.
function doThis()
{
if(condition)
return true;
else
return false;
}
But when you check the loop you have to call it one time only. After doing stuff you are again calling doThis() function it is wrong.
if(doThis())
{
goToPage2;
do stuff;
//doThis();
}
And also it depends on how you are calling this loop and functions.
For eg.,
<script>
var i = 0;
onPageLoad()
{
if(i%2==0){
return true;
i++;
}else{
return false;
i++;
}
}
if(onPageLoad()){
goToPage2;
doStuff();
}else{
onPageLoad()
}
</script>
Here when the condition meets the right statement which is i%2 == 0 it will automatically call goToPage2 function otherwise it again going to check the condition.
You can add interval/timeout in the loop to check when the variable is updating and when it calls goToPage2 function.
Hope this helps.
I have two statements in an if block that both link to a function that will return a bool. Both statements must be true for the code to run but I want them both to be checked even if the first one is false. The relevant code:
if (myFunc(one) && myFunc(two)) {
//execute
}
myFunc will execute some code before returning false, but this code is not executed on two if one returns false.
I got this to work, but it feels like a hack:
if ((myFunc(one) && myFunc(two)) || (myFunc(two) && myFunc(one))) {
//execute
}
Does anyone have a better solution? Thanks!
Another way:
var first = myFunc(one),
second = myFunc(two);
if (first && second) {
//execute
}
In this case both will be executed first and checked for non false values later.
use the & operator
take a look at this example
function a (){
console.log(1);
return true;
}
function b (){
console.log(2);
return false;
}
if(b() & a() == true){
console.log('asas');
}
How to break from objx(data).each(function(item) iteration when a certain condition is met.
My Json string is below:
var data= [{"field1": "0","field2": "2"},{"field1": "7","field2": "2"},{"field1": "1","field2": "5"}];
Here is a my code:
function iterate(){
objx(data).each(function(item){
if(item.field1 == "7"){
//doing some job;
return;
}
alert("after if is executed");// this alert coming inspite of giving
}); // return in if block
}
i think the return is only enabling it to come out of function but not from the loop. i dont want this unnecessary iteration once my condition is met and job is done.
can anyone suggest how to come out of this each loop?
return false;
Returning false breaks out of the each function.
To exit the jquery each loop
function iterate(){
objx(data).each(function(item){
if(item.field1 == "7"){
//to stop the loop here
return false; // here - will exit the each loop
}
});
}