Using function results in "function source code" and not evaluated function value? - javascript

The following code sample (also at http://jsfiddle.net/MZwBS/)
var items = [];
items.push({
example: function() {
if(0 > 1) {
return 'true';
} else {
return 'false';
}
}
});
document.write(items[0].example);
produces
'function () { if (0 > 1) { return "true"; } else { return "false"; } }'
instead of
'false'
It seems like I've been able something like this with ExtJS. Can anyone tell me where I went wrong? I'd like to evaluate anonymous functions like this on-the-fly.

Do you mean to execute it?
document.write(items[0].example());​

You want:
document.write(items[0].example());
When you skip the parentheses, you are saying, "Print this function." When you have them, you are saying, "Evaluate this function and print the result."

I've solved my issue by adding '()' after the anonymous function as shown below. http://jsfiddle.net/MZwBS/7/
var items = [];
items.push({
example: function() {
if(0 > 1) {
return 'true';
} else {
return 'false';
}
}()
});
document.write(items[0].example);
This code block now produces the expected result of
'false'

Related

Javascript micro optimisation for if statement

I am fairly new to JavaScript and I have a question regarding how to optimise if statements.
I will show you two scenarios.
//first
var number = 10;
var calculationOneResult = functionOne(number);
var calculationTwoResult = functionTwo(number);
if (calculationOneResult === true) {
//stuff
} else if (calculationTwoResult === true) {
//more stuffs
}
//second
var number = 10;
if (functionOne(number) === true) {
//stuff
} else if (functionTwo(number) === true) {
//more stuffs
}
Here is my question:
In the first scenario, I am calculating two times.
In the second one, if the first function returns true, will it calculate the second elseif statement or will it skip it after doing the stuff ?
The following code:
if(statement1) {
// stuff
} else if(statement2) {
// other stuff
}
is equivalent to
if(statement1) {
// stuff
} else {
if(statement2) {
// other stuff
}
}
as there is no elseif in JavaScript - see documentation.
So the answer is any function in statement2 will be simply skipped.
Nothing in an else clause executes if the if expression tests as true, so the second version of your code will definitely save a function call in such cases.

return a return in javascript

I want to write a assert() function in Js. Something like this:
assert = function(condition, message) {
if(condition) {
console.log(message);
} else {
return return;
}
}
But it's not true.
We can write it like this:
assert = function(condition, message) {
if(condition) {
console.log(message);
return true
} else {
return false;
}
}
And use that like this:
function () {
if(!assert(condition)) { return; }
//Other Lines
}
But it could be better if we were be able to use that like this:
assert(condition, 'OK');
Is it possible to return a return?
In fact have we any way to use something like to previous line to end a function by a assert?
Update:
My goal is end a function by a simple assert(condition) use, and not
with use second conditions like if(!assert(condition)) { return; }.
p.s: I'm a newbie.
How about throwing an exception from assert if not true and otherwise nothing. That way, you can use them as you might be familiar already from other languages.
Code example:
assert = function(condition, message) {
if(condition) {
console.log(message);
} else {
throw "Assertion failed!";
}
}
It seems to me you just want to write less code. If you want to write lots of asserts then consider having a function that processes your list for you, then you only need to maintain an array of parameters:
var list = [
[condition, 'OK'],
[condition2, 'OK'],
[condition3, 'OK'],
[condition4, 'OK']
];
function runAsserts(asserts){
for(var i = 0; i < asserts.length; i++){
if(!assert(asserts[i][0], asserts[i][1])) {
return;
}
}
}
Then you just call it with:
runAsserts(list);

Trying to write a function in JS passing through true and false statement

I have a little question. I want to write a function in javascript and the function needs to take two extra parameters, for when the function is true and false. But I don't know how to write it. So, I want something like this:
function greater (para1, para2, casetrue, casefalse) {
if (para1 > para2) {
casetrue
}
else {
casefalse
}
}
Is this possible? Because I wrote that function and than I called the function with
greater(5,3, function() { return "is greater" }, function() { return "is smaller" }) and it didn't work.
Can anybody please help?
Thanks in advance
try this way, otherwise you'll be returning a function:
function greater (para1,para2,casetrue,casefalse) {
if (para1 > para2) {
return casetrue();
} else {
return casefalse();
}
}
To make the function greater return "is greater" or "is smaller" one must return the return value of the parameter functions:
function greater(para1, para2, casetrue, casefalse) {
return (para1 > para2) ? casetrue() : casefalse();
}
Tested on Firefox 24.0 / Linux
function greater (para1, para2, casetrue, casefalse) {
if (para1 > para2) {
return casetrue();
}
else {
return casefalse();
}
}
Like has been suggested in other answers, the greater function is returning functions instead of strings. If this is the desired behavior, you can call the returned function with an extra pair of brackets:
greater(5,3, function() {return "is greater"},function() {return "is smaller"})()

How to exit (escape) a function from for loop inside of it?

This is theoretical question to understand how many escapes (return or exit) can apply to nested loops or other controls and functions.
I confused about this because I am stuck in the code
How to escape from for ... each loop and method at the same time?
I can't stop iterating over options in select element.
I tried return and return false already, but am unsuccesful.
Generally how we can do that?
function() {
for (...) {
if (...) {
$(...).each(function() {
// You have to exit outer function from here
});
}
}
}
Use a shared variable between the loops. Flip it to true at the end of the each() loop if you want to exit and at the end of the for-loop check for it being true. If yes, break out of it.
I would do it this way:
Create a boolean variable to check on each loop, and if the variable is true, then exit the loop (do this for each).
var exitLoop = false;
$(sentences).each(function() {
if(exitLoop) {return;}
var s = this;
alert(s);
$(words).each(function(i) {
if(exitLoop) {return;}
if (s.indexOf(this) > -1)
{
alert('found ' + this);
throw "Exit Error";
}
});
});
Note this is not the correct use of a try-catch as a try-catch should strictly be used for error handling, not jumping to different sections of your code - but it will work for what you're doing.
If return is not doing it for you, try using a try-catch
try{
$(sentences).each(function() {
var s = this;
alert(s);
$(words).each(function(i) {
if (s.indexOf(this) > -1)
{
alert('found ' + this);
throw "Exit Error";
}
});
});
}
catch (e)
{
alert(e)
}
Code taken from this answer
The loop can also be exited by changing the iterator value.
var arr = [1,2,3,4,5,6,7,8,9,10];
for(var i = 0;i<arr.length;i++){
console.log(i);
compute(i);
function compute(num){
//break is illegal here
//return ends only compute function
if(num>=3) i=arr.length;
}
}
"label"s are the solution for scope processes like breaking loops. Here is the built-in answer I realized after years: https://css-tricks.com/you-can-label-a-javascript-if-statement/
Not ideal but you can do
let result = false;
function() {
for (...) {
if (...) {
$(...).each(function() {
result = true;
});
}
}
if (result == true){
return;
}
}
As in most languages. The keyword to exit a loop is break;
More info here:
http://www.w3schools.com/js/js_break.asp

Returning variable from function is undefined once returned

Is there any reason that this:
function find_parent_p(x){
daddy = jQuery(x).parent();
if(daddy.attr("tagName").toLowerCase() == 'p'){
console.log(daddy,"result");
return (daddy);
} else {
find_parent_p(daddy);
}
}
jQuery(document).ready(function($){
$('img').each(function(){
next = find_parent_p($(this));
})
});
would return a jQuery object in the console (expected behaviour), where as the following returns Undefined All I am doing is moving the call to console.log outside the function, and after the call to it:
function find_parent_p(x){
daddy = jQuery(x).parent();
if(daddy.attr("tagName").toLowerCase() == 'p'){
return (daddy);
} else {
find_parent_p(daddy);
}
}
jQuery(document).ready(function($){
$('img').each(function(){
next = find_parent_p($(this));
console.log(next,"result");
})
});
You're missing the return statement in your else condition. If your function recurses, then the top level call won't return anything, and you'll end up with undefined.
else {
return find_parent_p(daddy);
}
I'm not sure if this is causing the problem, but the function only works if it finds the element immediately.
Make daddy a local variable (to prevent possible conflicts with global variables)
Return the result from the recursive call
:
function find_parent_p(x) {
var daddy = jQuery(x).parent();
if(daddy.attr("tagName").toLowerCase() == 'p') {
return daddy;
} else {
return find_parent_p(daddy);
}
}
Note: You can do the same using just jQuery:
var next = $(this).closest('p');
If you aim to get the img's parent which is p, you can use.
$('img').each(function(){
next = $(this).closest('p');
console.log(next,"result");
})

Categories