Will this code ever return false? - javascript

I'm reviewing some code where the logic looks flawed. I'm not sure if the following code will ever return false because of the if else return flow. My question is, will the following code ever return false, or even throw an error?
function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
var select = document.getElementById("selectmenusearch");
var selected = select.options[select.selectedIndex].value;
if(selected === 'organisation') {
submitSearchForm('<%= doOrganisationSearchURL %>');
} else {
submitSearchForm('<%= doIndividualSearchURL %>');
}
} else {
return false;
}
return true;
}
So the flow to me looks like
if (this condition is true) {
//execute some code
} else {
return false
}
else return true
NB: I know it would be better to refactor to have only one return statement but it looks to me like there are two else statements.

It depend of e.keyCode but if e.keyCode is not always equal to RETURN_KEY_CODE it will not always return false. You have 2 return. The first one is in the else of the first if so if e.keyCode !== RETURN_KEY_CODE, false is return. Else, you if will end normally and the instruction after it is return true.
function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
...
} else {
return false; // RETURN_KEY_KEYCODE !== e.keyCode
}
return true; // RETURN_KEY_KEYCODE === e.keyCode
}
I don't see any wait it can alway return false if e.keyCode is not always the same value. :)
If you want to make it more clear, you can just put the return in the end of the first if. Like that:
function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
...
return true; // RETURN_KEY_KEYCODE === e.keyCode
} else {
return false; // RETURN_KEY_KEYCODE !== e.keyCode
}
}

Just run a test. Seems like you were confused with what happens when there is more than one "return" statement in a function.
A return statement is a regular statement, just like any other - except for the fact that it will interrupt the local block execution and return flow control to the code that called the function. It is indifferent for you the fact that you have one, two, three returns... the language interpreter strictly follows the IF/ELSE rules - if a condition is met, then the block (delimited with "{ }" defined immediately under the if is the one that is executed, if the condition is not met, then the respective if's else block is executed. Whatever is the case, both if and else blocks, upon reaching their ends, will return flow to the next statement right after the if block (the if block is comprised by the if + else blocks), in the example here, "return true".
(function() {
if (k) {
console('k renders true');
}
else {
console.log('else reached');
return false;
}
return true;
console.log('bottom return true reached');
})();

Related

How to exit or break out from an else if

I've searched for a couple stackoverflow questions although couldn't find my answer.
I'm trying to break from an else if statement and was wondering if there was a more efficient way.
Heres a snippet:
var argument = "something";
if(argument == 'not_this'){
// this doesn't trigger
} else if(argument){
// this triggers although if the functions in here doesn't match what I want,
// how do I make It skip to the else statement without adding another else
// if statement?
} else {
// do something if both statements above fail
}
Is there something that I can do which exits from the else if(argument)... without adding another else statement? I've tried using switch and case although those don't seem to help.
Thanks.
You could set a flag that is by default true, and whenever the argument is valid you set it to false.
Then, to know when to execute the 'else' block, you can just check whether the flag is true or not:
var argument = "something";
let invalid = true
if (argument == 'not_this') {
// this doesn't trigger
invalid = false
} else if (argument) {
if (typeof argument != 'string') {
//valid
invalid = false
}
}
if (invalid) {
console.log('invalid')
}
Restructure the code to avoid confusing states, move out the if 'has value' check.
if (argument) {
if (argument === 'not_this') {
// this doesn't trigger
}
} else {
// do something if both statements above fail
}
For equality, it is safer to use strict equal === instead of loose equal ==
You could try using return; to break out of the statement, as that would stop all other code from being read.

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

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

Javascript Issue Checking if Value is Even

I'm trying to write a function that checks whether a value is odd or even, but it isn't quite working as it should, or rather, at all.
The code I got was from this question.
function isEven(value) {
if (value % 2 == 0) {
return true;
console.log("True");
}
else {
return false;
console.log("False");
}
console.log(value);
}
isEven(3);
I get no errors in the browser's console, but it also does not log True, False, or value.
Note: I will also accept jQuery solutions, but would prefer Javascript.
You are returning before logging. Anything after return will not be executed.
return after logging
function isEven(value) {
if (value % 2 == 0) {
console.log("True");
return true;
} else {
console.log("False");
return false;
}
}
isEven(3);
Ensure value is an integer first by parsing it with
parseInt(value)

Javascript multiple if true conditions

I neeed help with multiple if conditions.
if condition 1 & condition 2 true means I want both condition actions:
if(condition 1 true) {
$('.inner_wrapper').addClass('em-border-red');
return false;
}
if(condition 2 true) {
$('.cCal').addClass('em-border-red');
return false;
}
if(condition 3 true){
$('.cCal-row2').addClass('em-border-red');
return false;
}
But only one condition works.
Each of your if blocks contains a return statement. As soon as one condition is met, no further code will execute. This is, by definition, the behaviour of the return statement:
A return statement causes a function to cease execution and return a value to the caller
Since all of yours just return false, you should be able to move the return to after the conditions:
if(condition1) {
$('.inner_wrapper').addClass('em-border-red');
}
if(condition2) {
$('.cCal').addClass('em-border-red');
}
if(condition3) {
$('.cCal-row2').addClass('em-border-red');
}
return false;
Remove the return false; form each if block and try to manage it at the bottom, outside of if condition.
retVal = true;
if(condition 1 true)
{
$('.inner_wrapper').addClass('em-border-red');
retVal = false;
}
if(condition 2 true)
{
$('.cCal').addClass('em-border-red');
retVal = false;
}
if(condition 3 true)
{
$('.cCal-row2').addClass('em-border-red');
retVal = false;
}
return retVal;
You have two ways:
<!-- and condition //-->
if (a == b && a != c) {
// your stuff
<!-- or condition //-->
} else if (a == c || a ==b) {
// other stuff
<!-- otherwise //-->
} else {
// another stuff
}
Otherwise you have "switch case". Like on this page.

Categories