Calling function name inside function - javascript

There are some concept I still cannot figure out in Javascript. Like this one for example. I came across this code while searching for a function to return the greatest common divisor of two integers. I tested it but I can't understand how this returns the gcd. Please can explain anyone who understand explain what does return gcd(b, a % b); do here?
var gcd = function(a, b) {
if ( ! b) {
return a;
}
return gcd(b, a % b);
};

You are using a recusion, which is a pattern of calling the same function again with different paramters until an exit condition is found and then the recursion stops.
// exit condition
if (!b) {
return a;
}
In this case the function is called again with moved parameter b as a and a new parameter of b with a modulo b.
// call function again with different parameters
return gcd(b, a % b);

Related

How to fix a recursive hcf function?

I tried to make an HCF function in javascript using recursive functions as given in the code below. But somehow this only works for exact multiples of numbers (like 2,4 ; 52,104 etc). Co-prime numbers also gives 'undefined'. Please help me fix the bug.
I have tried substituting a local scope variable c = a % b. But this doesn't work out either.
The code:
function hcf(a, b) {
if (b == 1){
return 1;
} else if (a % b == 0){
return b;
} else {
hcf(a,a % b);
}
}
Test cases:
hcf(4,2);
hcf(108,52);
hcf(9,4);
Expected Outcomes:
2
4
1
Actual Outcomes:
2 [Correct]
undefined [Incorrect]
undefined [Incorrect]
The recursive case needs a return statement.

what does the code bellow does in javascript explanation?

function power(a,b){
return b--?a*power(a,b):1;
}
I don't understand that line of code b--?a*power(a,b):1
a function that returns the power of a number without using any math function like power(a,b) of a ** b
It'll be clearer if you move the b-- to its own line. Assuming that b is a positive integer, the code is equivalent to:
function power(a,b){
const bBeforeDecrement = b;
b--;
return bBeforeDecrement !== 0
? a * power(a,b)
: 1;
}
power recursively calls itself, multiplying the ultimate return value by a each iteration, decrementing b and recursively calling itself until b reaches 0.
At the end, the return value is a multiplied by itself b times.
Like the comment notes, the reassignment of b makes things more confusing than it needs to be - it would make more sense to subtract 1 from b in the recursive call instead:
function power(a,b){
return b > 0
? a * power(a, b - 1)
: 1;
}

Simple JavaScript Function that returns the parameter of greater value

I'm learning how to build functions and my task is to create a function declaration that will return the parameter of greater value. So far, I've only learned how to sums and products -- in other words, I don't know how to get JavaScript to "decide" which parameter is greater.
The extact task description is as follows: Build a function declaration called maxOf2 that takes in two numbers and returns the greater value. Be careful to think about the possibility of equality as well and return one of the numbers.
I've read about Math.max(), but as the course hasn't covered that, I'm not supposed to use it.
Here is what I have so far, which is not much:
function maxOf2(a, b) {
var a = 12;
var b = 4;
return ...;
}
Very basic example:
function maxOf(a, b){
if(a > b){
return a;
} else {
return b;
}
}
You can use that Math.max() function like so:
Math.max(a, b);
And another example that uses ternary operator:
function maxOf(a, b){
return a > b ? a : b;
}
Another answer because there are only 3 answers:
const maxOf = (a,b) => (a > b ? a : b);

What are reasons to use return as a function in JavaScript?

while I was going through concepts related to JavaScript functions, I came up with problem which I'm unable to figure it out. I use following codes i.e one with return as a function and the other as a simple function as follows
function plus(a, b) {
return(
console.log(a+b),
console.log(this),
console.log(arguments)
)
}
plus(4,5);
and
function plus(a, b) {
console.log(a+b),
console.log(this),
console.log(arguments)
}
plus(4,5)
But when I run both I'm not able to figure it out since both results same in console. So I just want to know when should I use return as function.? and what is its main purpose? I've seen answers here but those related to return entire function or objects but didn't find specific answer to return as a function. So please help me in it.
return(
console.log(a+b),
console.log(this),
console.log(arguments)
)
statement means:
return the argument that is represented by (...) expression. Here parentheses is not a part of a return keyword syntax, but is a standalone operator used in conjunction with operator ,.
The (1, 2, 3) expression after evaluating returns the value of the last expression.
In your case it's console.log(arguments) which returns undefined.
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
This
function plus(a, b) {
return(
console.log(a+b),
console.log(this),
console.log(arguments)
)
}
is an equivalent of this:
function plus(a, b) {
var r = (
console.log(a+b),
console.log(this),
console.log(arguments)
);
return r;
}
or simply this (EDIT, but is wrong, see zerkms comment ):
function plus(a, b) {
var r =
console.log(a+b),
console.log(this),
console.log(arguments);
return r;
}
where ,, is an expression - compute all parts delimited by commas with result of last expression.

JavaScript can return argument?

I have two functions:
function g(data, i){}
function f(data, i){}
I want to call them like:
var myVar = f(g(data, i));
So g() should return (data, i).
Of course, it doesn't work. Is there some way to do this?
Returning multiple values is not supported by Javascript (at least not in the implementations that most browsers have).
Do the following:
function g(data, i) {
// some code
return {
data: data,
i: i
};
}
var o = g(data, i);
f(o.data, o.i);
Note:
As mentioned by Phil in the Question's comments, if i is not modified in g(), then you can just call f(g(data, i), i) without modifying function g.
there is, if you use apply and make your functions return arrays of values.
function g(a, b) { return [a, b]; }
function f(c, d) { return [c, d]; }
console.log(f.apply(null, g("thing", "cow")));
This is, however, a great sign of a bad programmer if used for this purpose, so you don't want to do this. If you have functions that take two arguments, pass two arguments:
function g(a, b) { return [a, b]; }
function f(c, d) { return [c, d]; }
var result = g("thing", "cow");
f(result[0], result[1]);
because you already know it takes, and generates, a pair of values, or use the object pattern (rather than an array) that Der Flatulator shows you.
Not exactly like you have it, however you can trick it since arguments is "array-like" ... behold :D
var g = function(a,b) {return [a,b]};
var f = function(a, b) {console.log("f evaluating", a, b)};
f.apply(null,g(1,2));
gives you:
bar 1 2
Alternatively you could do something hacky in your (f) function to split the values of the first argument if there is only one argument passed in, but I like the apply better, especially cuz this is horrible if for example your a argument is an array by itself.
Works for any number of argument length
function g(){
return [].slice.call(arguments);
}
function f(data, i){
}
f.apply(undefined, g(data, i));

Categories

Resources