recursion javascript code example

Example 1: recursive function javascript

function pow(x, n) {
  if (n == 1) {
    return x;
  } else {
    return x * pow(x, n - 1);
  }
}

alert( pow(3, 3) ); // 27

Example 2: javascript recursion over array

function recurse(arr=[])
{
  	// base case, to break the recursion when the array is empty
    if (arr.length === 0) {
    	return;
    }
  	
  	// destructure the array
	const [x, ...y] = arr;
  
  	// Do something to x
  	
  	return recurse(y);
}

Example 3: recursion in javascript

var countdown = function(value) {
    if (value > 0) {
        console.log(value);
        return countdown(value - 1);
    } else {
        return value;
    }
};
countdown(10);

Example 4: java recursion

public void removeDigits(String string) {
  if(string.length == 1) {
    if(Character.isDigit(string.CharAt(0))) {
      return "";
    } else {
      return string;
    }
  } else {
    if(Character.isDigit(string.CharAt(0))) {
      return removeDigits(string.substring(1));
    } else {
      return string.substring(0, 1) + removeDigits(string.substring(1));

public static void main(String[] args) {
  String string = "1a2b3c"
  System.out.println(removeDigits(string)); //will print "abc"
}

Tags:

Java Example