return statement in Javascript? - javascript

I have my JavaScript code as:
$('[id^="thresholdParameter_"]').each(function(i, value) {
//any field is edited
if($(this).val() !== previousThresholdParameters[i]){
alert('Hello');
return true;
}
});
Here I want that once it reaches return true; it must come out of the function and return the true value. However, it it keeps on iterarting.
Why is it so? return in JavaScript does not function like return in Java??

Use return false instead of return true, as return true treated as continue and return false as break in $.each loop,
$('[id^="thresholdParameter_"]').each(function(i, value) {
//any field is edited
if($(this).val() !== previousThresholdParameters[i]){
alert('Hello');
return false; // use false
}
});
From $.each()
We can break the $.each() loop at a particular iteration by making the
callback function return false. Returning non-false is the same as a
continue statement in a for loop; it will skip immediately to the next
iteration.

Return false in each callback will only stop the each function.
See last example from jQuery each API: http://api.jquery.com/each/
You can try this:
var conditionMet = false;
$(selector).each(function() {
if (innerConditionMet) {
conditionMet = true;
return false; // stop the each
}
});

Try this since in your case it looks like you want to return true and used somewhere else:
var flag = false;
$('[id^="thresholdParameter_"]').each(function(i, value) {
//any field is edited
if($(this).val() !== previousThresholdParameters[i]){
alert('Hello');
flag = true;
return false;
}
});

var x = $('[id^="thresholdParameter_"]');
for(i in x){
if(x[i] !== previousThresholdParameters[i]){
alert('Hello');
return true; //
break;
}
}

retun false to break out of $.each()
try this fiddle for better understanding: http://jsfiddle.net/patelmilanb1/q348g/
<div class="number">
<h1>1</h1>
<h1>2</h1>
<h1>3</h1>
<h1>4</h1>
<h1>5</h1>
<h1>6</h1>
<h1>7</h1>
</div>
$('.number h1').each(function () {
var h1Value = $(this).text();
if (h1Value == 5) {
return false;
} else {
$(this).css("background-color", "#F1F1EF");
}
});
it will add background colour to all h1 untill it reaches number 5 and then breaks out of $.each loop

Related

jQuery function doesn't exit after return [duplicate]

How do I break out of a jQuery each loop?
I have tried:
return false;
in the loop but this did not work. Any ideas?
Update 9/5/2020
I put the return false; in the wrong place. When I put it inside the loop everything worked.
To break a $.each or $(selector).each loop, you have to return false in the loop callback.
Returning true skips to the next iteration, equivalent to a continue in a normal loop.
$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
According to the documentation return false; should do the job.
We can break the $.each() loop [..] by making the callback function
return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
BTW, continue works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
http://jsfiddle.net/9XqRy/
I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.
I would like to explain it with 2 simple examples:
1. Example:
In this case, we have a simple iteration and we want to break with return true, if we can find the three.
function canFindThree() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
return true;
}
}
}
if we call this function, it will simply return the true.
2. Example
In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.
function canFindThree() {
var result = false;
$.each([1, 2, 3, 4, 5], function(key, value) {
if(value === 3) {
result = true;
return false; //This will only exit the anonymous function and stop the iteration immediatelly.
}
});
return result; //This will exit the function with return true;
}
"each" uses callback function.
Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block

If Else Statement Not working inside .each()

When submit the form it runs both means to say code inside if is running and after else code is also running.
$("#new_chq").submit(function(){
var inputs = document.getElementsByName("val_2[]");
var i;
for (i = 1; i <= inputs.length; i++) {
$('#file_'+i).each(function() {
if(!$('#file_'+i).val() == ''){
$('#text_'+i).attr('required', '');
return false;
}
else{
return true ;
}
});
}
});
As you can see in docs:
We can break the $.each() loop at a particular iteration by making the
callback function return false. Returning non-false is the same as a
continue statement in a for loop; it will skip immediately to the next
iteration.
So, you need to move the form event handling after the jQuery each-loop.
Here is an example:
$("#new_chq").on('submit', function() {
var isValid = true;
$('[id^=file_]').each(function() {
if($(this).hasAttr('required') && !$(this).val()) {
isValid = false;
return false; // <- this breaks the loop
};
});
return isValid;
});
Please note, there are other errors in your code, such as $('#file_'+i).each loop, which has no sense - that is one element with unique id.

Illegal break statement in $.each [duplicate]

How do I break out of a jQuery each loop?
I have tried:
return false;
in the loop but this did not work. Any ideas?
Update 9/5/2020
I put the return false; in the wrong place. When I put it inside the loop everything worked.
To break a $.each or $(selector).each loop, you have to return false in the loop callback.
Returning true skips to the next iteration, equivalent to a continue in a normal loop.
$.each(array, function(key, value) {
if(value === "foo") {
return false; // breaks
}
});
// or
$(selector).each(function() {
if (condition) {
return false;
}
});
According to the documentation return false; should do the job.
We can break the $.each() loop [..] by making the callback function
return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
BTW, continue works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.
$('.groupName').each(function() {
if($(this).text() == groupname){
alert('This group already exists');
breakOut = true;
return false;
}
});
if(breakOut) {
breakOut = false;
return false;
}
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
http://jsfiddle.net/9XqRy/
I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.
I would like to explain it with 2 simple examples:
1. Example:
In this case, we have a simple iteration and we want to break with return true, if we can find the three.
function canFindThree() {
for(var i = 0; i < 5; i++) {
if(i === 3) {
return true;
}
}
}
if we call this function, it will simply return the true.
2. Example
In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.
function canFindThree() {
var result = false;
$.each([1, 2, 3, 4, 5], function(key, value) {
if(value === 3) {
result = true;
return false; //This will only exit the anonymous function and stop the iteration immediatelly.
}
});
return result; //This will exit the function with return true;
}
"each" uses callback function.
Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
I use this way (for example):
$(document).on('click', '#save', function () {
var cont = true;
$('.field').each(function () {
if ($(this).val() === '') {
alert('Please fill out all fields');
cont = false;
return false;
}
});
if (cont === false) {
return false;
}
/* commands block */
});
if cont isn't false runs commands block

Breaking out of .each()

I want to break out of .each() iterations and it doesn't allow me to. Here is my code. Thanks for the help guys! Appreciate it.
$('#btn-submit-add').click(function(){
var answerField = 1;
$('.addAnswerChoice').each(function(){
var answerChoice = $(this).val();
if (answerChoice == ""){
$('#answerChoice-'+answerField+'-Error').show();
$(this).focus();
return false; // this doesn't work
}
answerField++;
});
alert('doing stuff after');
});
My guess is that you're trying to return false from the click handler to cancel the submit. The way you have it your return false statement returns from the function you passed to .each(), which does break out of the .each() loop but it doesn't return from the outer function that is the click handler. So execution then continues with the statement after the .each(), i.e., the final alert. And your click is not cancelled. Try this instead:
$('#btn-submit-add').click(function(e){
var answerField = 1;
$('.addAnswerChoice').each(function(){
var answerChoice = $(this).val();
if (answerChoice == ""){
$('#answerChoice-'+answerField+'-Error').show();
$(this).focus();
e.preventDefault();
return false;
}
answerField++;
});
});
jQuery passes the event object to your click handler (notice I've added a parameter called e), so you can use event.preventDefault() to stop the click from working.
This solution is almost like each only but short-circuits when the first true value is returned. So, you don't have to explicitly break out of the iterations.
Array.prototype.slice.call(document.getElementsByClassName("addAnswerChoice")).some(function(item) {
var answerChoice = item.value;
if (answerChoice == ""){
$('#answerChoice-'+answerField+'-Error').show();
item.focus();
return true;
}
return false;
});
From documentation:
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
Edit:
if #nnnnnn is right, the code should look like:
$('#btn-submit-add').click(function(){
var validated = true;
var answerField = 1;
$('.addAnswerChoice').each(function(){
var answerChoice = $(this).val();
if (answerChoice == ""){
$('#answerChoice-'+answerField+'-Error').show();
$(this).focus();
validated = false;
return false;
}
answerField++;
});
if (!validated)
{
return false;
}
alert('doing stuff after');
});

Why does this function return true instead of false

Here is my test:
var test = function () {
$.each([1, 2], function () {
if(true !== false) { // it is just an example
alert('I am here');
return false; // how should I make the function test to stop or to exit here?
}
});
return true;
}​;
alert(test());
​
I would like the test function to return false but it returns true.
Why? How should I fix the code? Please see the comments for more details.
Returning false from the .each() callback just halts the .each() iteration. It doesn't return from the enclosing function; the only way to do that in JavaScript is to throw an exception.
What you could do is set a flag:
var test = function () {
var abort = false;
$.each([1, 2], function () {
if(true !== false) { // it is just an example
alert('I am here');
abort = true;
return false; // how should I make the function test to stop or to exit here?
}
});
return !abort;
}​;
It returns true because the inner return false returns the anonymous function, which only instructs jQuery to end the $.each loop early.
Use a variable outside the inner function to properly juggle the return status.
var test = function () {
var retVal = true;
$.each([1, 2], function () {
if(true !== false) { // it is just an example
alert('I am here');
retVal = false;
return false;
}
});
return retVal;
}​;
You could also change your code to not use the $.each method, if a simply for...in loop would suffice:
var test = function () {
var retVal = true;
for (var value in [1, 2]) {
if(true !== false) { // it is just an example
alert('I am here');
return false;
}
};
return true;
};
That is because return false; just breaks out of the $.each loop.. but not the function.
It returns true from the last statement
fix it by changing your code to:
var test = function () {
var returnValue = true;
$.each([1, 2], function () {
if(true !== false) { // it is just an example
alert('I am here');
returnValue = false;
return false; // how should I make the function test to stop or to exit here?
}
});
return returnValue;
}​;
You have two function definitions:
Inner Function (in $.each): returns false
Outer Function (window.test): returns true
Capture when exited:
var arr = [1,2,3,4,5,6,7,8,9];
var breakpoint = undefined;
$.each(arr, function(i,val){
if (val==4){ // some break condition
breakpoint = {index:i,val:val};
return false;
}
return true;
});
console.log('break point:', breakpoint); // breakpoint.index=3, breakpoint.val=4
Then in your outer function you can do something like return typeof breakpoint !== 'undefined';, or set a returnValue as others have suggested.

Categories