Functions in JavaScript

Functions

Functions in JavaScript are declared using the function keyword. A function declaration creates a function that's a Function object having all the properties, methods, and behaviors of Function objects. By default, functions return the value undefined; to return any other value, the function must have a return statement that consists of the return keyword followed by the value to be returned (this can be a literal value, a variable, or even a call to a function).

EXAMPLE

Take some time to review the code below that declares functions and prints their return values.

Input Format

The first line contains a string denoting .
The second line contains two space-separated integers, and , to be summed.

'use strict';
process.stdin.on('data', function (data) {
    let input = String(data).split(new RegExp("[\n ]+"));
    main(input[0], +(input[1]), +(input[2]));
});
/**** Ignore above this line. ****/

function greetings(name) {
    console.log("Hello, " + name);
}

function sum(a, b) {
    return a + b;
}

function main(name, a, b) {
    greetings(name);
    console.log(sum(a, b));
}
Run
Input
Output

The Function Expression

A function expression is very similar to (and has almost the same syntax as) a function statement. The main difference between a function expression and a function statement is the function name, which can be omitted from a function expression to create an anonymous function. Function expressions are often used as Immediately Invoked Function Expressions (IIFEs), which run as soon as they're defined.


Unnamed Function Expression

EXAMPLE

The code below demonstrates an unnamed function expression.

Input Format

A single integer denoting .

'use strict';
process.stdin.on('data', function (data) {
    main(+(data));
});
/**** Ignore above this line. ****/

function main(input) {

    /**
    *   Defines an unnamed function and assigns it to a variable named square. 
    *   @param {Number} x
    *   @returns {Number} The value of argument squared.         
    **/
    var square = function(x) {
        return x * x;
    };

    // Print the value returned by passing input as x to the 
    // anonymous function referenced by variable square
    console.log(square(input));
}
Run
Input
Output


Named Function Expression

EXAMPLE

The code below demonstrates a named function expression.

Input Format

Two space-separated integers describing the respective values of and .

'use strict';
process.stdin.on('data', function (data) {
    let input = String(data).split(new RegExp("[\n ]+"));
    main(+(input[0]), +(input[1]));
});
/**** Ignore above this line. ****/

function main(factN, fibN) {

    /**
    *   Defines a named recursive function as a property of the math variable. 
    *   @param {Number} n
    *   @returns {Number} The value of n factorial.         
    **/
    var math = {
        // Declare the factorial property
        factorial: 
            // Declare the function as the property's value
            function factorial(n) {
                if (n > 1) {
                    return n * factorial(n - 1);
                }
                // Returns 1 if n <= 1
                return 1;
            }
    };

    /**
    *   Defines a named recursive function referenced by the fib variable. 
    *   @param {Number} n
    *   @returns {Number} The value of fibonacci(n).         
    **/
    var fib = function fibonacci(n){
        if (n > 2) {
            return fibonacci(n - 1) + fibonacci(n - 2);
        }
        else if (n < 1) {
            return 0;
        }
        // else, return 1
        return 1;
    }

    // Print the value returned by passing factN as n to the 
    // function referenced by variable math:
    console.log(math.factorial(factN));
    // and by passing fibN as n to the function referenced by variable fib:
    console.log(fib(fibN));

}
Run
Input
Output

RecursionRecommended Article
View

Recursion

 
Go to Top

Recursion

Recursion

This is an extremely important algorithmic concept that involves splitting a problem into two parts: a base case and a recursive case. The problem is divided into smaller subproblems which are then solved recursively until such time as they are small enough and meet some base case; once the base case is met, the solutions for each subproblem are combined and their result is the answer to the entire problem.

If the base case is not met, the function's recursive case calls the function again with modified values. The code must be structured in such a way that the base case is reachable after some number of iterations, meaning that each subsequent modified value should bring you closer and closer to the base case; otherwise, you'll be stuck in the dreaded infinite loop!

It's important to note that any task that can be accomplished recursively can also be performed iteratively (i.e., through a sequence of repeatable steps). Recursive solutions tend to be easier to read and understand than iterative ones, but there are often performance drawbacks associated with recursive solutions that you're going to want to evaluate on a case-by-case basis. Typically, we use recursion when each recursive call significantly reduces the size of the problem (e.g., if we can halve the dataset during each recursive call). Regardless of the advisability of recursively solving a problem, it's extremely important to practice and understand how to recursively solve problems.

Example (Java)

EXAMPLE
The code below produces the multiple of two numbers by combining addition and recursion.

Input Format
Two space-separated integers to be multiplied.

import java.util.*;

class Solution {
    // Multiply 'n' by 'k' using addition:
    private static int nTimesK(int n, int k) {
        // Print current value of n
        System.out.println("n: " + n);

        // Recursive Case
        if(n > 1) { 
            return k + nTimesK(n - 1, k);
        }
        // Base Case n = 1
        else { 
            return k;
        }
    }
    public static void main(String[] args) {
    	Scanner scanner = new Scanner(System.in);
        int result = nTimesK(scanner.nextInt(), scanner.nextInt());
        scanner.close();
        System.out.println("Result: " + result);
    }
}
Run
Input
Output

The diagram below depicts the execution of the code above using the default input (4 4). Each call to nTimesK is represented by a bubble, and each new recursive call bubble is stacked inside and on top of the bubble that was responsible for calling it. The function recursively calls itself using reduced values until it reaches the base case (). Once it reaches the base case, it passes back the base case's return value () to the bubble that called it and continues passing back k + the previously returned value until the final result (i.e.: the multiplication by addition result of ) is returned.

Recursion 2.png

Once the code hits the base case in the bubble, it returns (which is ) to the bubble.
Then the bubble returns , which is , to the bubble.
Then the bubble returns , which is , to the bubble.
Then the bubble returns , which is , to the first line in main as the result for , which assigns to the variable.

 
Related challenge for Recursion
Go to Top
  1. Challenge Walkthrough
    Let's walk through this sample challenge and explore the features of the code editor.1 of 6
  2. Review the problem statement
    Each challenge has a problem statement that includes sample inputs and outputs. Some challenges include additional information to help you out.2 of 6
  3. Choose a language
    Select the language you wish to use to solve this challenge.3 of 6
  4. Enter your code
    Code your solution in our custom editor or code in your own environment and upload your solution as a file.4 of 6
  5. Test your code
    You can compile your code and test it for errors and accuracy before submitting.5 of 6
  6. Submit to see results
    When you're ready, submit your solution! Remember, you can go back and refine your code anytime.6 of 6
  1. Check your score