Javascript program yields undefined (recursion) [duplicate] - javascript

This question already has answers here:
Simple Recursive Javascript Function Returns Undefined
(2 answers)
Closed 4 years ago.
Hello I am a newbie learning Js
I am trying to learn about recursion but I stuck in here
var isEven = (number) =>{
number = Number(number)
if(number === 0){
console.log('it is even')
return true;
}
else if(number === 1){
return false;
}
else{
number = number - 2;
isEven(number);
}
}
console.log(isEven(50) === true)
why the end result becomes undefined? Thank you for the help

Add return in recursion call:
function isEven(number){
number = Number(number)
if(number === 0){
console.log('it is even');
return true;
}
else if(number === 1){
return false;
}
else{
number = number - 2;
return isEven(number);
}
}
console.log(isEven(50));

You must use return in recursion call .If u do not use return the isEven(50) function will run but do not return isEven(48) so your function isEven(50) get undefined.So always use return.
Example
function factorial( n ) {
if ( n === 1 ) {
return 1;
}
return n * factorial( n - 1 );
}
In above example you can when we call factorial(n-1); it will return (n-1)*factorial(n-2); but if u remove the return then result is undefined as factorial(n-1); do not return anything.
Always remember in recursion focus is on returning function again and again till we get the result.

Related

Function that takes a number as an argument and returns a boolean javascript

I am new to coding and I have this exercise where I have to write a function that takes a number as argument and returns a boolean. This is the code I wrote but is not working and I am getting the warning
"The function should only have a return statement in its body. You can evaluate a boolean expression an return immediately its value"
var even = function(x) {
if ((x % 2) === 0) {
return true;
} else
return false;
};
The response you get from the code submission has an important point:
The expression (x%2)===0 is already a boolean, so you can return that expression:
return x%2 === 0;
In general you should avoid this pattern:
if (some_boolean_expression) {
return true;
} else {
return false;
}
... since the boolean you return is exactly the same as the boolean expression that is evaluated in the if condition. So it should be just:
return some_boolean_expression;
you can just write your function like this
var even = function(x)
{
return x % 2 === 0
}
var even = function(x) {
if (typeof x === "number") {
if (x % 2 === 0) {
return true
} else {
return false
}
} else {
return false
}
}
This covers all the edge cases

why recursion is returning undefined in javascript? [duplicate]

This question already has answers here:
Recursive function returns undefined
(3 answers)
Closed 4 years ago.
I'm using recursion to reverse the number. in the terminating condition i am returning the result. but it's returning "undefined". the console inside the if is showing the correct output.
// reverse the number
var result= "";
var reverse = function(x) {
if(x == 0){
console.log("result",result);
return result;
}else{
var lastDigit = x % 10;
result += lastDigit;
x = Math.floor(x/10);
reverse(x);
}
};
console.log(reverse(73254));
That's because you're not returning a call to function itself and by default undefined is returned.
The solution is to return the result from reverse(x).
Also, you can simplify your function like this:
var reverse = function(x) {
if(x < 10)
return x;
return x % 10 + "" + reverse(Math.floor(x/10));
};
console.log(reverse(73254));
If you do not return anything from function with return then by default undefined is returned. You have to return the function from else like:
return reverse(x);
Working Code Example:
var result= "";
var reverse = function(x) {
if(x == 0){
console.log("result",result);
return result;
}else{
var lastDigit = x % 10;
result += lastDigit;
x = Math.floor(x/10);
return reverse(x);
}
};
console.log(reverse(73254));

about detecting if a number is odd or even in javascript

I am working on a tutorial for JS on CodeAcademy and I am asked to create a function to check if the input is divisible by 2.
Here is my code:
var isEven = function(number) {
if (number % 2 ===0) {
return true;
}
else if (!isNaN(number)) {
return "Give a number";
}
else {
return false;
}
};
Why does codeacademy tell me that the code is wrong because the function will result in true for 3?
!isNaN(3) -> evaluates to true
if (typeof(number) === "number"){
return (number%2 === 0)
} else {
//do something else
return false
}
In JavaScript, anything that is not "falsy" is true. So, your string "Give a number" is considered to be true.
Reverse your sign on !isNaN i.e. remove the exclamation point - needs to be negative in construct
But really you shouldn't be returning text either.
Try this:
var isEven = function(number) {
if (!isNaN(number)) {
return "Give a number";
}
else if (number % 2 ===0) {
return true;
}
else {
return false;
}
};

why doesn't this backtracking recursion go to other branches?

Given an array, and a goal (number), I have to determine if it is possible to reach goal by adding elements from the array.
Here is my code (in javascript), and some results:
function check(goal,array) {
function add(sum, array) {
if (sum == goal)
return true;
else if ((sum > goal)||(!array[0]))
return false;
else
console.log(sum); // check where we are
return add(sum + array.shift(),array) || add(sum,array);
}
return add(0,array);
}
What I expect to happen to the stack of add() after calling check(6,[1,3,5])
add(0,[1,3,5]) // log 0
add(1,[3,5]) //log 1
add(1+3,[5]) //log 4
add(1+3+5,[]) //return false
add(1+3,[]) //return false
add(1,[5]) //log 1
add(1+5,[]) //return true
add(1,[])
add[0,[3,5])
add(0+3,[5])
add(0+3+5,[])
add(0+3,[])
add(0,[5])
add(0+5,[])
add(0,[])
Actual results:
check(6,[1,3,5])
false
0
1
4
check(3,[1,3,5])
false
0
1
1
It never leaves the first branch!
Why ?
Edit:
Ok, based on the suggestions, I guess it's better to avoid passing array as an argument:
function check(goal,array) {
function add(sum, i) {
if (sum == goal)
return true;
else if ((sum > goal)||(i==array.length))
return false;
else
console.log(sum);
return add(sum + array[i],i+1) || add(sum,i+1);
}
return add(0,0);
}
It works fine here.
It's the same array that's passed around, and after the first branch it'll become empty so the recursion will finish. Try it with a copy:
function check(goal,array) {
function add(sum, array) {
if (sum == goal)
return true;
else if ((sum > goal)||(!array[0]))
return false;
else
print(sum);
array = array.slice();
return add(sum + array.shift(),array) || add(sum,array);
}
return add(0,array);
}

Function supposed to return a boolean returns undefined

Trying to come up with a function to check if a number is prime and I'm running into trouble. I'm sure there's a simpler way to do this, but why would this function not return false, for the number 9? It returns false for even numbers but for any other type of composite number it returns undefined, but since it prints NOT PRIME it should also be returning false.
function isPrime(n, i) {
document.writeln(i);
var nextNum = i + 1;
var number = n;
if (i < n) {
if ((n % i) === 0) {
document.writeln("NOT PRIME");
return false;
} else {
document.writeln(nextNum);
isPrime(number, nextNum);
}
} else if (i === n) {
document.writeln("Recursion ends");
return true;
} else {
document.writeln("Confused" + typeof i + typeof n);
}
}
You need to return the value of the recursive call, i.e., change
isPrime(number, nextNum);
to
return isPrime(number, nextNum);
You are missing a return in this branch after the recursive call to isPrime:
if ((n % i) === 0) {
document.writeln("NOT PRIME");
return false;
} else {
document.writeln(nextNum);
isPrime(number, nextNum);
}
I think that you want to change it to:
if ((n % i) === 0) {
document.writeln("NOT PRIME");
return false;
} else {
document.writeln(nextNum);
return isPrime(number, nextNum);
}
Because you aren't returning anything in that branch, the true/false calls are disappearing.
It should just need one parameter to check if prime.
Try this out:
function isPrime(num){
// An integer is prime if it is not divisible by any prime less than or equal to its square root
var squareRoot = parseInt(Math.sqrt(num));
var primeCountUp = function(divisor){
if(divisor > squareRoot) {
// got to a point where the divisor is greater than
// the square root, therefore it is prime
return true;
}
else if(num % divisor === 0) {
// found a result that divides evenly, NOT prime
return false;
}
else {
// keep counting
return primeCountUp(++divisor);
}
};
// start # 2 because everything is divisible by 1
return primeCountUp(2);
}
Adding the high of the "square root" from here

Categories