function return on javascript - 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.

Related

How to call the second function after the first function is executed completely?

I'm new to JavaScript. I have 2 javascript functions below. Basically, I want the the first function is run until the user fills out the textbox. Otherwise the textbox will get focused forever. After the first function is completely executed, the second function will be kicked off to display an alert saying everything is satisfied, the system is sending email to supervisor. Is it possible that I just put the entire second function into the first function so that the second function will be executed after the first function is completely done? Can someone give me any advices? I appreciate your help and thanks a lot.
function DisableUpdateBtn(txtAnimal)
{
If(txtAnimal.text == "")
{
Alert("Animal is required!");
txtAnimal.focus();
return false;
}
Return true;
}
function AllowToUpdate(ckbApprove,txtUserApproval)
{
If(ckbApprove.checked && txtUserApproval.text != "")
{
Alert("Conditions are met! Sending Approval to Supervisor!");
Return true;
}
return true;
}
Use a callback function, for example:
function runMeFirst(callback)
{
/** Some code here. **/
if (typeof callback == 'function')
callback();
}
function anotherFunc()
{
alert('Another Func!');
}
Usage
runMeFirst(anotherFunc);
runMeFirst(function () {
/** Your code here. **/
});

Check both conditions in an if statement even if the first one is false

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');
}

Running Javascript functions in order (one after the other)

when I try the following:
if(myFunction() == "3") {
alert('its three!');
}
my function returns undefined, when I know that it is actually returning 3.
Is this because javascript evaluates the if statement before the function can return a value?
if so how can I do something like this:
var result = myFunction();
// Wait until result is there
if(result == "3") {
alert("its three!");
}
To troubleshoot your problem, try calling the "alert" function with the return value of your function as the argument:
var result = myFunction();
// For debugging
alert(result);
if(result == "3") {
alert("its three!");
}
If the contents of the alert box are "undefined", your function is not in fact returning a value, and just assigning that non-existent result to a variable is not going to help. Check to make sure myFunction looks like:
function myFunction() {
// Perform calculations
var n = 10 - 7;
// Return result
return n;
}
The JavaScript interpreter requires neither functions to return values nor return statements to be used. That means you should double-check that there is in fact a return statement. If you are assigning the result to a variable first, that can be one way you could miss that return statement.
If you are dealing with Ajax requests, jQuery "modal dialogs," or similar constructs, it is not even possible for a function to return a value in this way (when the button is clicked or the request completes, that is). To fix the problem, your function needs to accept a callback function as a parameter. Then when done, it must call that function, passing the "returned value" as an argument:
function myFunction(callback) {
// Start an AJAX request
var x = new XMLHttpRequest();
x.open('GET', '/domath.php?expression=10-7', true);
x.onreadystatechange = function() {
if(x.readyState == 4 && x.status == 200) {
// Call callback function, "returning" a value asynchronously
callback(x.responseText);
}
};
x.send();
}
And then your main code would be:
myFunction(function(result) {
// For debugging
alert(result);
if(result == "3") {
alert("its three!");
}
});
What it sounds like is that your javascript code is calling the function before the function or the elements it accesses (ie something in the DOM) have been fully loaded, which is why the function call is returning undefined instead of '3'.
The way to prevent this is to defer calling the function until the DOM has finished loading.
This is typically done by having the function call in your document.onload() method, which only gets run when the page has finished loading, or by using jQuery's $.ready() method, which again waits until the page is ready before being run.
Hope that helps.
I am a little unclear as to what you are doing from the description. Try this to see if its what you wanted:
function MyFunction(){
var result
// Do something here
//dummy:
result = 3;
return result;
}
var Testing = MyFunction();
alert(Testing);
if (Testing == 3) {
alert("Holy Cow! Its 3!");
}

How to break out of .each() and return a value for a function

I want to use return false to break a .each() but also return a value at the same time. How can I do this?
Please refer to a work-around function to see what I am trying to do:
function HasStores(state) {
var statehasstores = false;
$(stores).each(function (index, store) {
if (state == store.state && store.category == "meyers") {
statehasstores = true;
return false; // break
}
});
return statehasstores;
}
What Id like to do in pseudo code is:
Function () {
for() {
if found {
return true;
}
}
return false;
}
You're doing it right...
Quote from http://api.jquery.com/each/
"We can stop the loop from within the callback function by returning false."
Be creative:
try {
$(stores).each(function (index, store) {
if(state == store.state && store.category == "meyers"){
throw store;
}
});
}
catch(e) {
// you got e with the value
}
No, I was just kidding, don't use this :). It came as an idea I liked to share.
Use a variable outside the loop to get the value and use it afterward.
var value;
$(stores).each(function (index, store) {
if(state == store.state && store.category == "meyers"){
statehasstores = true;
value = store; // added line
return false; //break
}
});
alert(value);
The way you're doing is just fine. I've tested on jsFiddle, see an example here.
It's not working for you? Can you show more context?
jQuery .each
Alternatively, you could use a for loop instead of each(), and just return the value.
What you're suggesting is the way to do it. I'd think of it less as a workaround and more as an idiom.
How about:
$.each( myObj, function( key, value ){
...
if( sthg... ){
myObj.somethingWentHorriblyWrong = true;
return false;
}
});
if( myObj.somethingWentHorriblyWrong ){
// ... do something, not forgetting to go:
delete myObj.somethingWentHorriblyWrong;
}
PS I was initially interested in what $.each(... actually returns. As it says on the relevant JQ page, "The method returns its first argument, the object that was iterated", but in fact the solution doesn't even require that you use that fact...
PPS Need a function that returns a value? Wrap in an outer function of course.
Okay I guess there's a little doubt about this point so maybe I'm making it clearer here :
When jquery doc says : "We can stop the loop from within the callback function by returning false." and you do :
Function () {
for() {
if found {
return true;
}
}
return false;
}
This doesn't mean that you're function will return true when find the searched element. Instead, it will always return false.
So to make your function work as you whish I propose to do so :
Function () {
variable found = false;
foreach() {
if found {
found = true;
return false; // This statement doesn't make your function return false but just cut the loop
}
}
return found;
}
Of course there are many other ways to perform this but I think this is the simplest one.
Coopa - Easy !
As others have noted from jQuery Each, returning false will only break from the loop not return the value, returning true however will 'continue' and immediately begin the next iteration. With that knowledge, you could somewhat simplify your code like this:
function HasStores(state) {
var statehasstores = false;
$(stores).each(function (index, store){
// continue or break;
statehasstores = !(state == store.state && store.category == "meyers"))
return statehasstores;
});
return !statehasstores;
}
This of course is a little silly using the double negative, and has the side effect of saving 'true' to statehasstores for every false iteration and vice versa, however the end result should be the same and you no longer have that if statement.

Break out of function within enumarable.each iteration

I have a Prototype class - within the class i call a function and within this function i do en enumerable.each iteration. If an element within this iteration fails a check i then call another function which then re-calls this same function later. Can i break within this iteration so not only the iteration is ended but nothing else within the function is called.
Say with this code i wouldnt want the console.log to be called if elm.something == 'whatever'. Obviously i could set a variable and then check for this after the function but is there something else that i should be doing?
myFunction: function(el){
el.each(function(elm){
if(elm.something == 'whatever'){
this.someOtherFunction(elm);
}
},this);
console.log("i dont want this called if elm.something == 'whatever'");
}
Just to be clear, in this case the console.log is just placeholder code for the beginnings of some additional logic that would get executed after this loop
You answered it yourself
"Obviously i could set a variable and then check for this after the function"
In this case, you're basically looking to not call the console.log even if elm.something == 'whatever' for a single 'elm'
myFunction: function(el){
var logIt = true;
el.each(function(elm){
if(elm.something == 'whatever'){
logIt = false;
this.someOtherFunction(elm);
}
},this);
logIt && console.log("i dont want this called if elm.something == 'whatever'");
}
The simplest way would be to avoid using each() and instead rewrite using a for loop:
myFunction: function(el){
for(var i in el) {
var elm = el[i];
if(elm.something == 'whatever'){
return this.someOtherFunction(elm);
}
}
console.log("i dont want this called if elm.something == 'whatever'");
}

Categories