Minimum
function min(a,b){
if (a < b) return a; else return b;}
console.log(min(0,10));
console.log(min(0,-10));
Recursion
function isEven (a){
if (a == 0) return true;
else if (a == 1) return false;
else return isEven (a - 2);
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??
the console.log for -1 returns error message “maximum stack call exceeded”, because the function recalls itself until 0 or 1 is reached, but a number less than one has no command to return “true” or “false”; this can be fixed by adding this line: else if (a < 0) return isEven(-a); before this line: else return isEven (a - 2);
Bean counting
function countBs(string) {
return countChar(string, “B”);
}
function countChar(string, c) {
let count = 0;
for (let i = 0; i < string.length; i++) {
if (string[i] == c) {
count += 1;
}
}
return count;
}
console.log(countBs(“BBC”));
// → 2
console.log(countChar(“kakkerlak”, “k”));
// → 4