Moses wrote:
Hi
I have a nested function which works properly but I need to have a
slight change in it where I could not do that
Please don't post code with tabs, use 2 or 4 spaces for indenting.
The Original function
function addSquares(b)
The function name is confusing: why 'addSquares'? There is no addition
involved.
{
function square(a)
{
d = a*b;
You should keep d local with var:
var d = a*b;
But it isn't needed, consider:
function square(a) {
return a*b;
}
return d;
}
return square;
}
t = addSquares(2)(2);
The function seems unnecessarily convoluted.
But What I need is before returning the square I need to do a small
validation to check weather d 10 , based upon that I need to return d
or return square.
You can't make calling square conditional on the value of d since you
have to call square to find out what the value of d is.
Once square is called, d is a number. If you return d you will be
trying to evaluate d(2), which will result in an syntax error.
I need to change the function like this
function addSquares(b)
{
function square(a)
{
d = a*b;
return d;
}
t = square
That makes t a reference to the function square.
if(t>10)
Since t is a function object, trying to evaluate whether it is greater
than 10 doesn't make sense.
{
return 'Greater';
}
else
{
return t;
}
}
t = addSquares(2)(2);
I don't think I understand what you are trying to do. It seems you
want a function that takes two arguments. If the first is 10 or less,
return the product. If it's larger, return the first value.
A simple function to do that is:
function foo(a, b){
if (a 10) return a;
return a*b;
}
--
Rob