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 -20Below 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;
}
Comments