return true, breaks code in javascript - javascript

Having the following code:
function test(x) {
if(x=='a') return false;
return true;
}
if(y ==x) {
return test('a');
group['ids']= inputs.val();
console.log(group);
}
why return true simply breaks my code by not continuing beyond the return?
Note: I want the return test()'s answer to control if either it should continue with the code OR not
Update
I already do something like:
var response = test('b');
if (response==false) return false;
... more code here ...
But I want to avoid having to do so on every invoke of that function

Because that's what return does in almost every programming language: it
exits the function and
returns a value
If you need other code to be executed, put it before the return statement.
Edit: I saw your edit, but it doesn't change the very nature of return in that (and every) context. It will continue to stop the flow of the current scope, returning to the nearest higher scope with a value (in your case, true or false).

The keyword return, as it name suggests, returns the program flow control to the calling function and optionally sets the function's return value.
This works the same way in every C-like language.
What you probably wanted to do is a Delphi-like approach, where the keyword Result works differently - it just sets the return value that will be used when the function terminates, but does not immediately terminate the function.
function() {
var result = someDefaultValue;
if (someCondition)
result = otherValue;
if (otherCondition)
result = yetAnotherValue;
return result;
}

try putting return at the end because return true will break the execution and nothing will execute after that

When a return statement executes, the execution of the current function ends, and control of the program is returned to the context that invoked the function. Anything after a return statement will not be executed.

The return keyword causes a function to end ('return') when the interpreter reaches that keyword and does not continue to process anything after the return statement (in that same function).
You could rewrite what you have:
group['ids']= inputs.val();
console.log(group);
return true;

I typically find out which scenarios are bad/errors and return false; out of them, THEN continue on to the code which is correct.
function Testmcdooder (test) {
if (test === false) {
// just exit up here
return false;
}
// now all of this code will run only if we're fine
group['ids']= inputs.val();
console.log(group);
}

The return statement exists from the function. I think that you rather want an if statement:
if (y == x) {
if (test('a')) {
group['ids']= inputs.val();
console.log(group);
}
}
If you also want to return the value after determining if the other statemens should run:
if (y == x) {
if (test('a')) {
group['ids']= inputs.val();
console.log(group);
return true;
} else {
return false;
}
}
Alternatively:
if (y == x) {
var cond = test('a');
if (cond) {
group['ids']= inputs.val();
console.log(group);
}
return cond;
}

Related

Best practice for returning value

I have often wondered if it is bad practice to allow sequential execution to decide the return value and termination point. EG (this is a question surrounding IF statements, so ignore the fact there are myriad better ways to do this simple function!):
function isGreaterthanTen(val) {
if(val > 10) return true;
return false;
}
Same effect, is smaller but maybe less readable than:
function isGreaterthanTen(val) {
if(val > 10) {
return true;
} else {
return false;
}
}
So is one better than the other, best practice wise and/or min-wise?
You should avoid writing so called spaghetti code. That means, one should be able to read your code without jumping from one place to another in order to untangle and understand it. Having return statement in the middle of your code can be considered a spaghetti code, especially in longer functions.
I prefer having one return statement that returns a variable, which I declare at the top of the function and manipulate throughout the execution.
function isGreaterthanTen(val) {
let isGreater = false;
if (val > 10) {
isGreater = true;
}
return isGreater;
}
of course that function can be shortened to:
function isGreaterthanTen(val) {
return val > 10;
}
A one exception from this rule which I'd allow is at the top of the function when you validate the data and prevent the execution:
function isGreaterthanTen(val) {
if (typeof val !== 'number')
return;
return val > 10;
}
which fill return nothing if the parameter isn't a number.
At my current work - Leads never advise to use single line execution without brackets stating readability lacks there.
if(true) {
return 'good practice'
}
if(true)
return 'bad practice'
Another related point I always follow is checking for negative value first
if(false) {
return 'this is the negative case'
}
return 'case for most of the positive case'
However I know different ways to just handle such single line returns
If just boolean than you can simply return the condition
function foo(){
return 1 === 1
}
console.log(foo())
You can use coerced value for just boolean value if your value is treated as truthy or falsy and not a boolean
function foo() {
return !!1 // 1 treated as true
}
console.log(foo())
If you have two different values to get returned so you probably use ternary too.
function foo() {
const me = 'satyam',
friend = 'jack',
satyamAge = 23
return satyamAge === 20 ? me : friend
}
console.log(foo())

how to avoid repeating return false line

On many functions I have this line:
if (!$('.postitle').hasClass('pmarked')) {return false;}
To avoid repeating it so often I tried this:
function falsea(){
if (!$('.postitle').hasClass('pmarked')) {return false;}
}
and then call the above - falsea() instead of if (!$('.postitle')...
It doesn't work.
Is there any simillar way to avoid repeating entire line each time ?
The level is incorrect.
return false actually do nothing but stop your function for further running.
If you are not outputing any result, this is just same as simply write return.
So in your falsea() function, your return false stop the function, not the outer one but the falsea() itself, it won't make the mother do anything.
What you can do is
function falsea(){
return $('.postitle').hasClass('pmarked'))
}
In mother,
if (!falsea()) return
It doesn't work.
It doesn't work because that's not how functions work (in any language, really). A return statement in the callee doesn't cause the caller to terminate. Simple example:
function foo() {
console.log('before bar()');
bar();
console.log('after bar()');
}
function bar() {
console.log('in bar; before return');
return false;
console.log('in bar; after return');
}
foo();
What you can do is put the condition in its own function to reuse that, but you still need an if statement in every caller:
function hasPmarked(){
return $('.postitle').hasClass('pmarked');
}
// in caller
if (!hasPmarked()) {
return false;
}
Is there any simillar way to avoid repeating entire line each time ?
You could create a function that accepts a callback and only executes the callback if the check succeeds.
For example:
function doStuffIfPMarked(stuff) {
if ($('.postitle').hasClass('pmarked')) {
stuff();
}
}
Then the caller can do:
doStuffIfPMarked(function() {
// do something
});
I.e. if you had this before:
function foo() {
if (!$('.postitle').hasClass('pmarked')) {return false;}
// do my stuff
}
you would write
function foo() {
doStuffIfPMarked(function() {
// do my stuff
});
}
You still need to repeat some code, but you are abstracting the condition logic away.
Your function will only return false or undefined.
Try adding at the end
return true;
Or even simpler, just do:
return !$('.postitle').hasClass('pmarked')
Keep in mind that the return doesn't propogate so you will still need check the return value of this function and return.
if (falsea()) {return false;}

What is the difference between using `return` outside and inside of conditions?

What is the difference between using return in outside of else condition and inside of else condition?
I know the best code is without use else and I know both are doing similarly same. Is there difference or advantages?
function f1() {
if (1 == 1) {
return true;
} else {
return false;
}
}
function f2() {
if (1 !== 1) {
return true;
} else {
return false;
}
return false
}
console.log(f1());
console.log(f2());
Not related to your previous question, but only this:
In Method:2, the last return statement (ie return true;) is virtually useless. Because last line in the SaveVersionMainScreen() won't be executed as there is if and else both conditions are present. Which should account for all cases.
if you have if statement within block code and contains return in both if and else block. Its mean either if block will execute and return from method or else block will execute and return. Other statements below that blocks will not execute and compiler may give you error something like
Statements cannot be reached
For Example:
SaveVersionMainScreen() {
let element = this.commonValidation(true);
if (element) {
return false;
}
else{
return true;
}
// Below statements will never run
var a=2;
var b=3;
var c=4;
return true;
}
Way to go changing you question completely. Leaving my answer anyway for now.
Your version 2 is bad practice, code would not work in a strict language like Java as you have a return statement that cannot be reached. As for your test removing the else from your function should solve it for you, but the issueseems to be with the test and not your code.
SaveVersionMainScreen() {
let element = this.commonValidation(true);
if (element) {
return false;
}
return true;
}

Break execution from function

Is possible to break execution program from function or I need to check boolean val returned?
Code
function check(something) {
if (!something) return;
// Else pass and program continuing
}
check(false); // I want to stop execution because function has returned
// Or I need to check value like if (!check(false)) return; ?
// I want easiest possible without re-check value of function..
alert("hello");
One way would be to through an Error, but otherwise you would need to use a boolean check, yes. I would recommend to use the boolean
function check(something) {
if (!something) throw "";
// Else pass and program continuing
}
check(false); // I want to stop execution because function has returned
// Or I need to check value like if (!check(false)) return; ?
// I want easiest possible without re-check value of function..
alert("hello");
Easiest...
(function(){
function check(something) {
if (!something) return false;
// Else pass and program continuing
}
if(!check(false)) return;
alert("hello");
});
(function(){ ... }); is called IIFE Immediately-invoked function expression.
Put your code in an IIFE, then you can use return
(function() {
function check(something) {
if (!something) {
return false;
} else {
return true;
}
}
if (!check(false)) {
return;
}
alert("hello");
});

Is it possible to know if function uses empty return statement?

Is it possible to know if a function uses an empty return statement versus simply not using the return keyword?
For example:
function noReturn(){ }
function useReturn(){ return; }
console.log( noReturn() ); // undefined
console.log( useReturn() ); // undefined
I know all about WHEN and WHY one would use an empty return statement, I just want to know if you can tell if return; was used at all versus no return statement.
I'm assuming that its not possible, and thats ok. If there was any cool Function prototype trick I didn't know of, that would be sweet.
Edit: Not trying to solve any particular problem, unless general curiosity is a problem. :)
You cannot distinguish return values of these three functions:
function a() { }
function b() { return; }
function c() { return undefined; }
according to JS specification.
No, it's not possible to differentiate these:
return undefined;
return;
End of function without returning any value
First, both return undefined; and return; return the same:
12.9 The return Statement
ReturnStatement :
return ;
return [no LineTerminator here] Expression ;
A return statement causes a function to cease execution and return a
value to the caller. If Expression is omitted, the return value is
undefined. Otherwise, the return value is the value of Expression.
A ReturnStatement is evaluated as follows:
If the Expression is not present, return (return, undefined, empty).
Let exprRef be the result of evaluating Expression.
Return (return, GetValue(exprRef), empty).
And then, it does not matter if you used return; or nothing, because [[Call]] will return undefined:
13.2.1 [[Call]]
If result.type is throw then throw result.value.
If result.type is return then return result.value.
Otherwise result.type must be normal. Return undefined.
I think this is a toy problem, but here is a possible approach to this problem. Convert the function to a string, then for all instances of a valid return statement anywhere in the string replace them with confederate return statements. Execute this modified function using eval() and observe what is returned.
For example,
function foo(){ return; }
function bar(){ if(0) return; }
becomes
function foo(){ return 'return;'; } // "return;"
function bar(){ if(0) return 'return'; } // undefined
This way whatever path the logic follows in the function, if something is explicitly returned, we can know what form it takes. If nothing is returned, due to design or logic flow, then 'undefined' is returned. Consider the following function:
function inspectReturn(fcn) {
var str = fcn.toString();
// Anytime we see a 'return something' we replace it with return 'something'
str = str.replace(/(\b)return \s*(\S[^\n;}]+)/mg, "$1return '$2'");
// Anywhere we see a lone 'return' we replace it with return 'return'
str = str.replace(/(\b)return\s*([\n;}])/mg, "$1return 'return;'$2");
eval("fcn="+str);
return fcn();
}
We can then observe the return values from the the below sample functions:
function noReturn(){ } // undefined
function useReturn(){ return } // "return;"
function useReturn2(){ return; } // "return;"
function useReturn3(){ return true; } // "true"
function useReturn4(){ if(0) return; } // undefined
function useReturn5(){ return undefined } // "undefined "
function useReturn6(){ var _return = " return "; return _return; } // "_return"
Demo: JSBin
Note: Voice your opinion about how the regex can be improved all you wish. You might be able to break it (and congratulations to you), but there are simple and concrete JavaScript parsing rules for validating return statements, so on such a toy problem it's up to the reader to properly implement them. Also, if something is thrown, then catch blocks exist for that. However, this is a sufficient demo IMHO.
Quite apart from knowing that JavaScript does not differentiate these. A way for checking might be:
function noReturn(){ }
function useReturn(){ return; }
function foo(){
var _return = "return";
}
function fooReturn(){
var _return = "return";
return _return;
}
function fooReturn2(){
var _return = "return";
return;
}
console.log(/return\s*(\w*);?\s*}\s*/.test(noReturn.toString())); //false
console.log(/return\s*(\w*);?\s*}\s*/.test(useReturn.toString())); //true
console.log(/return\s*(\w*);?\s*}\s*/.test(foo.toString())); //false
console.log(/return\s*(\w*);?\s*}\s*/.test(fooReturn.toString())); //true
console.log(/return\s*(\w*);?\s*}\s*/.test(fooReturn2.toString())); //true

Categories

Resources