How to call 2 child functions in one main function - javascript

I have several functions in JavaScript whose results I want to use in an if statement in another function.
My problem is that only the first listed child function seems to be returning a result. When I swap the order of the functions around then I still only get a returning result from the child function listed first.
I'm a beginner and not all that familiar with functions just yet. See my example below. Please be specific with any answers.
function main(a) {
return functone(x); // name of function is actually "functone" for this example
return functtwo(y); // name of function is actually "functtwo" for this example
if(functone(x)!="true") {
return false;
} else {
if(functtwo(y)!="true) {
return false;
} else {
return true;
}
}
}

You can't return two values from one function. So your code should be
function main(a){
if(functone(x)!="true")
{return false;} else
{if(functtwo(y)!="true")
{return false;} else {return true;}
}
}

It appears that you want to only want to return true only if both of the called functions do.
A typical pattern for this would be:
function main(a) {
return functone(x) && functwo(y);
}
Note that in this case functwo will only be called if the result of funcone is false (or more strictly "falsey", i.e. also including null or 0) because the && operator is what's called a short circuit operator. If the result of the operation can be determined directly from the left hand operand, the right hand operand is not evaluated.
If you want functwo to be called regardless of the outcome of funcone then replace the && operator with the bitwise & operator.
Note that your funcXXX functions ought (like this function) to return the propert boolean value true or false, and not the string "true".

Related

If/Else Statement Not Evaluating

I have a little helper function that is not evaluating on either the If or Else.
I know the function is being called because I have the nlapiLogExecution, which is how you debug in NetSuite. Notes on what is being logged are with the code.
How is this possible? I have tried to use == operator as well. I also tried to set it as a variable inside the function (which I don't think is necessary).
function convertUnit(unit, cubicMeters){
nlapiLogExecution('DEBUG','convertUnitFunction',typeof(unit))
// typeof is String
nlapiLogExecution('DEBUG','convertUnitFunction',unit)
// value is Each
if (unit === 'Each'){
return cubicMeters
nlapiLogExecution('DEBUG','equals Each', cubicMeters)
// does not log here
}
else {
nlapiLogExecution('DEBUG','else statements', 'equals else')
// Does not log here
}
}
You are entering the if statement, but the function returns before you can log anything. Try switching the order of the return and log statements:
function convertUnit(unit, cubicMeters){
nlapiLogExecution('DEBUG','convertUnitFunction',typeof(unit))
// typeof is String
nlapiLogExecution('DEBUG','convertUnitFunction',unit)
// value is Each
if (unit === 'Each'){
nlapiLogExecution('DEBUG','equals Each', cubicMeters)
// will log something now if you pass 'Each'
return cubicMeters
}
else {
nlapiLogExecution('DEBUG','else statements', 'equals else')
// will log something if the else branch is taken
}
}
You are returning before it gets to the nlapiLogExecution in the 'Each' section. Not sure why it isn't running on the else though, unless you are only passing 'Each'

Multiple return in function not working

I have many function inside one main function validate which doesn't work for some reason.However if the function validate contain a single function it works
function validate() {
return textcheck("txtname");
return numcheck("txtnum");
// textcheck and numcheck function are here
//doesn't work
}
function validate() {
return textcheck("txtname");// works fine
}
function validate() {
return numcheck("txtnum"); // works fine
}
why does 2 return inside a function don't work
Why it doesn't work
return exits a function, so code after the first return will never run.
Consider these functions:
function logs() {
console.log('I have been called');
return;
}
function doesNotLog() {
return;
console.log('I will not be called');
}
The first function does log a message to the console because console.log is called before return.
The second function doesn't, because return exits the function before console.log is called.
Fixing your example
If you want to return true if both textcheck and numcheck return a truthy value, you could use the logical AND operator &&:
// Returns true if both checks pass
function validate() {
return textcheck("txtname") && numcheck("txtnum");
}
If you need either of the two tests to pass, use the OR operator ||:
// Returns true if either check passes
function validate() {
return textcheck("txtname") || numcheck("txtnum");
}
If you want to return the status of each individual check, you could return an object:
function validate() {
return {
textCheck: textcheck("txtname"),
numCheck: numcheck("txtnum")
}
}
return exits the function when it's encountered, so your second return will never be reached.
If your goal is to return a truthy value* if either of two function calls returns a truthy value, you can use ||:
function validate() {
return textcheck("txtname") || numcheck("txtnum");
}
That calls textcheck and, if it returns a truthy value, returns that value; if textcheck returns a falsey value, it calls numcheck and returns its result.
If you want to return a truthy value if both of two functions returns a truthy value, you can use &&:
function validate() {
return textcheck("txtname") && numcheck("txtnum");
}
That calls textcheck and, if it returns a falsey value*, returns that value; otherwise it calls numcheck and returns its result.
I suggest working through some basic JavaScript tutorials.
* "truthy value" and "falsey value": JavaScript's && and || operators don't always result in true or false like they do in many other languages. Instead, they look for "truthy" values (values that coerce to true) or "falsey" values (values that coerce to false). The falsey values are 0, "", NaN, null, undefined, and of course, false; the truthy values are everything else.
Return in function terminate him.
If you want to validate two (or more) values use one return statement.
function validate() {
return textcheck("txtname") && numcheck("txtFname");
}
This solution may help you if you need to return 2 values at the same time. You just need to return a json object
function validate() {
return {
txtname : textcheck("txtname"),
txtnum : numcheck("txtnum")
}
}
After you call the function, you can get your values like this :
var result = validate();
// result.txtname
// result.txtnum
Looking at your code, I assume you want the validate() return you success (true) if both textcheck() and numcheck() succeed. Try this -
function validate() {
return textcheck("txtname") &&
numcheck("txtnum");
}

What is the point of the return in Javascript?

I've recently been learning javascript and came across the return statement or whatever it is. I've watched tutorials on it and I still don't get the point of it. Do I ever need it for anything and can someone please explain in detail what it does? Thanks
The return statement has multiple uses:
1) Return early from your function before the end of the function body. This is often within a branch of the code as in:
function whatever()
// do some things
if (err) {
console.log(err);
return err;
}
// other code here that will not execute if there was an err
}
2) Return a specific value back to the caller as in:
function add(a, b) {
return a + b;
}
var sum = add(3,4);
console.log(sum); // will show 7
The return statement in javascript can be used by itself to just exit the current function call and not return a specific value or it can be used to return a specific value.
If no return statement is present in a function, then the function will execute to the end of the function body and will return automatically at the end of the function body.
The only point of it is to send a value (string, number, or other values) from your function so that is can be used outside the function. Instead you can use global variables but that takes up more code, so it's a shortcut instead.
jfreind00 above said that you can use it to branch off early but that's what break. Here is the syntax:
function HiThere(something) {
if (something === true) {
break;
}
alert("Hi");
}
In this case, if something is true, then exit the function, if not then say hi.
Return would be like this:
function HiThere(something) {
if (something === true) {
return "Value to return: " + something;
}
alert("Hi");
}
In this case, if something is true, then exit the function and return Value to return: true, if not then say hi but don't return anything back.
Here's the most common use of the return statement:
document.getElementById("demo").innerHTML = myFunction(5,3); // Call a function
// to set the "demo" element to the value of: 5 * 3
function myFunction(a,b) {
return a * b;
}
<p id="demo"></p>
Use it to return a value. Your value could be "Yes", "false", "hello world" or "eat dirt." You can then run certain code based on the returned value.
Hope this helps!

function return on javascript

I am reading a book about javascript and I came across this syntax
this is a function
function unwantedTextEvent(){
return (navigator.vendor == 'Apple Computer, Inc.' && (event.target == event.relatedTarget.parentNode
|| (event.eventPhase == 3 && event.target.parentNode == event.relatedTarget)));
};
and then inside another function , the author is doing just this
attachEventListener(li, 'mouseover', function(e){
if (unwantedTextEvent()) { return; }
clearTimeout(closetime);
if (branch == li) { branch = null; }
//and so on
Now, I am ashamed to admit that I have never seen that syntax again :
if (unwantedTextEvent()) { return; }
and I dont have a clue what it does. Can anybody please explain to me? What does this syntax does in general?
Thanks in advance
That syntax calls a function called unwantedTextEvent(). If that function returns an affirmative Boolean value, then the callback function(e) inside of attachEventListener is returned.
It simply stops executing in the callback function.
Basically, unwantedTextEvent() is just a big condition. If that condition is true, it stop running the function
The code after a return is never run.
It is the same as doing :
if (!unwantedTextEvent()) {
clearTimeout(closetime);
if (branch == li) { branch = null; }
//and so on
}
Return exits the function immediately. That syntax exits without returning a value.
It's an ordinary if statement. The general form of if is:
if (<test expression>) {
<code to execute>
}
optionally followed by an else clause (but your example doesn't have this).
In this case, <test expression> is a call to the function unwantedTextEvent. If it returns a true value, the <code to execute> is executed, and the function returns. Otherwise, it continues with the rest of the function.
the return; statement simply exits out of the function passed into the attachEvenListener. i.e. the anonymous function.

Is there a benefit to using a return statement that returns nothing?

I'm refactoring a large javascript document that I picked up from an open source project. A number of functions use inconsistent return statements. Here's a simple example of what I mean:
var func = function(param) {
if (!param) {
return;
}
// do stuff
return true;
}
Sometimes the functions return boolean, sometimes strings or other things. Usually they are inconsistently paired with a simple return; statement inside of a conditional.
The problem is that the code is complex. It is a parser that uses a multitude of unique RegEx matches, creates and destroys DOM nodes on the fly, etc. Preliminary testing shows that, in the above example, I could change the return; statement to become return false;, but I'm concerned that I may not realize that it had a negative impact (i.e. some feature stopped working) on the script until much later.
So my questions: Is there a benefit to using a blank return statement? Could this have been intentionally coded this way or was it just lazy? Can I change them all to return false;, or return null; or do I need to dig through every call and find out what they are doing with the results of those functions?
Using return without a value will return the value undefined.
If the value is evaluated as a boolean, undefined will work as false, but if the value for example is compared to false, you will get a different behaviour:
var x; // x is undefined
alert(x); // shows "undefined"
alert(!x); // shows "true"
alert(x==false); // shows "false"
So, while the code should logically return true or false, not true or undefined, you can't just change return; to return false; without checking how the return value is used.
"Blank return" statements can be used to transfer the control back to the calling function (or stop executing a function for some reason - ex: validations etc). In most cases I use blank return statement is when I'm doing some kind of a validation. However, I make it a point to set some indicator as to why the execution of the function is stopped. For example, set the "innerText" property on a DIV element with the error message.
In the code above, it looks like it is a validation. The function returns a "true" if everything went well. It looks like the calling function parses the return value, and if it is "true", next step of statements (in the calling function) are executed.
It is a good practice to return "false" instead of a blank return in the above example. That way you make it all uniform and make life easy for other programmers.
You could fix such inconsistencies; however, make sure you test all the changes thoroughly. It is a good practice to test each change you make to the code, however small it may be.
There is no difference at all between return; and return undefined;. The result of calling both functions is to receive the value undefined.
(There's a very small specification-level difference between a function body that terminates with return vs. just falling off the end of the code, but it's nothing that can be detected in code.¹ Calling a function where execution falls off the end of the code also results in the value undefined.)
"use strict";
// Implicit return of `undefined`
function x() {
return;
}
// Explicit return of `undefined`
function y() {
return undefined;
}
// Execution falls off the end
function z() {
}
console.log(typeof x() === "undefined"); // true
console.log(typeof y() === "undefined"); // true
console.log(typeof z() === "undefined"); // true
Unless, of course, something has shadowed undefined. Which is still sadly possible (though not, gladly, at global scope). In that very edgy edge case, there's a difference:
"use strict";
(function() {
const undefined = 42;
// ^^^^^^^^^^^^^^^---- shadowing `undefined`
// Implicit return of `undefined`
function x() {
return;
}
// Explicit return of `undefined`
function y() {
return undefined;
}
// Execution falls off the end
function z() {
}
console.log(typeof x() === "undefined"); // true, `x` returns the canonical `undefined`
console.log(typeof y() === "undefined"); // false, `y` returns 42
console.log(typeof z() === "undefined"); // true, `z` (effectively) returns the canonical `undefined`
})();
¹ Using return is an abrupt completion that [[Call]] converts to a normal completion w/value. Falling off the end of the code is a normal completion (spec) (that [[Call]] ensures supplies undefined for the value). But again, this is a specification level difference, not something that's observable in code.
What MIGHT be lost here (not direct with your example) is that you can then have a tri-state object:
var myfunc = function(testparam) {
if (typeof testparam === 'undefined') return;
if (testparam) {
return true;
}
else {
return false;
}
};
var thefirst = myfunc(true)
var thesecond = myfunc(false);
var thelast = myfunc();
alert("type:" + typeof thefirst+" value:"+thefirst);
alert("type:" + typeof thesecond+" value:"+thesecond);
alert("type:" + typeof thelast+" value:"+thelast);
these return:
> type:boolean:true
> type:boolean:false
> type:undefined:undefined
note: null would return false in this example myfunc(null);
Changing your functions will actually alter the code because return; and return false; output different data types.
var test = function (x) {
if (!x) {
return;
}
else {
return false;
}
};
var a = test(true), b = test(false);
console.log(typeof b); // undefined
console.log(typeof a); // boolean

Categories