Question #38210

function multiplyAbsolute(number ,factor)
{
function multiply(number)
{
return number*factor;
}
if (number <0)
return multiply(-number)
else multiply(number);

}
pleas explain this code and also tell me how to call the above function
1

Expert's answer

2014-01-08T13:06:24-0500

Answer on Question #38210, Programming, AJAX | JavaScript | HTML | PHP

Provided function gets the number and factor and performs multiplying of absolute value of the number (i.e. non-negative value) and the factor.

The mathematical notation of function's result is:

|number| × factor

Here is the example of function results for some (number, factor) pairs:


multiplyAbsolute(2,3) is 6
multiplyAbsolute(-2,3) is 6
multiplyAbsolute(5,-4) is -20
multiplyAbsolute(-5,-4) is -20


Below is the function code with comments.


//main function body, gets number and multiplier values
function multiplyAbsolute(number ,factor)
{
//inner function body, not accessible outside main function, gets
number, performs multiplying
function multiply(number)
{
return number*factor;
}
//check if number is negative
if (number < 0)
return multiply(-number); //if number is negative, change
it to positive, call the inner function
else multiply(number); //if number if positive, perform no
changes, call the inner function
}


The example of the function call:

alert(multiplyAbsolute(-3 ,4));

The code above would show popup window with function result: 12.

Also, the function result can be stored for later usage:


var result;
result = multiplyAbsolute(-3 ,4));


The code above would set result variable value to 12.

Please note that Javascript has built-in method to get absolute value: Math.abs(). The function can be simplified significantly using given method:


function multiplyAbsolute(number ,factor)
{
return Math.abs(number)*factor;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS