Functions

Functions can be thought of as blocks of code that perform particular tasks. In JavaScript, like in most other programming languages, functions can take in a number of arguments and return a value.

The syntax to declare a function is as follows:

function functionName(arg1, arg2, ...) {
    // do something
    return something; // optional
}

A function can take any number of arguments, and the arity of a function is the number of arguments it can take

  • A nullary function takes in no arguments,

  • A unary function takes in 1 argument,

  • A binary function takes in 2 arguments,

  • A ternary function takes in 3 arguments, and so on

A function can return any value, or can return no value at all. In this case, the return type of the function is undefined. An example is the console.log function which logs something to the console and has no return value.

An example of a unary function is below:

function sumToN(n) {
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        sum += i;
    }
    return sum;
}

This function uses a for loop to calculate the sum of numbers from 1 to its input n. You could instead use the formula:

function sumToN(n) {
    return n * (n + 1) / 2;
}

To call a function on a value, use the name of the function and pass in the argument(s) (if any) in brackets:

sumToN(10); // returns 55

Here are some more functions:

function nullary() {
    console.log("hello");
    return 2;
}

function binary(x, y) {
    let k = x ** y;
    let m = k % y;
    return m + y;
}

function ternary(x, y, z) {
    let a = x + y + z;
    let b = x - y + z;
    return a / b;
}

function noReturnUnary(x) {
    console.log(x);
}

When calling a function in JS, if you pass in more arguments than is accepted by the function, JS ignores the extra arguments. If you pass in less arguments that is required by the function, JS replaces the missing values with the value undefined. This is different from other languages which throw an error if you pass in the wrong number of arguments.

Variadic functions

Sometimes you may want to create a function that can take in a variable number of arguments. These functions are called variadic functions. The syntax to declare a variadic function is as follows:

function variadic(...args) {
    // do something
}

In the function body, args can be treated as an array with a length property and indexing.

Python has a sum function that can take in any number of numbers and returns their sum. Let's recreate this in JavaScript:

function sum(...nums) {
    let total = 0;
    for (let i = 0; i < nums.length; i++) {
        total += nums[i];
    }
    return total;
}

To use a variadic function, simply call the function and pass in any number of arguments:

sum(3, 43, -4, 7.6, 9); // returns 58.6

Lambda functions

Let's go back to our sumToN function:

function sumToN(n) {
    return n * (n + 1) / 2;
}

Note that we only have one line in the function body, a return statement that performs a relatively simple math operation. Yet just for this one line return statement we need 2 extra lines to declare the function. Fortunately, JavaScript provides a way to shorten such one-line functions using lambda functions. The syntax to declare a lambda function is as follows:

let lambdaFunction = (arg1, arg2, ...) => something;

This is equivalent to:

function lambdaFunction(arg1, arg2, ...) {
    return something;
}

Since the let keyword creates a variable, this means that lambdaFunction can be reassigned to a different value. This is bad - what if we accidentally reassign our function to a different value? Instead, we use the const keyword, which declares a constant. As the name suggests, constants cannot have their values reassigned once assigned.

Now with all this in mind, let's rewrite out sumToN function:

const sumToN = n => n * (n + 1) / 2;

Calling a lambda function is same as calling a regular function:

sumToN(4); // returns 10
sumToN(10); // returns 55
sumToN(100); // returns 50500

Lambda expressions can have any arity (i.e. can take any number of arguments) and can be used to write functions that span multiple lines by using curly braces {}:

const sum = (...nums) => {
    let total = 0;
    for (let i = 0; i < nums.length; i++) {
        total += nums[i];
    }
    return total;
}

We have now rewritten the sum function from before as a lambda expression. Note that when writing multiline lambda expression, the return keyword needs to be present.

Lambda expressions work best when there is just one return statement in the function body; if there are multiple lines then it is better to use a regular function declaration.

Alternate syntax for lambda expressions

Lambda expressions can also be declared as below:

// the sum function from earlier
const sum = function(...nums) {
    let total = 0;
    for (let i = 0; i < nums.length; i++) {
        total += nums[i];
    }
    return total;
};

// the sum to n function from earlier
const sumToN = function(n) {
    return n * (n + 1) / 2;
};

This is more useful for complex anonymous functions with long bodies.

Higher order functions

Higher order functions are functions that take in function(s) as argument(s) and/or return a function. A simple example of a higher order function is a mapper function:

function map(func, val) {
    return func(val);
}

Here, the map function takes in two arguments: a function func and a value val. It then applies the function func to the value val and returns the result.

Let's try using this function:

// this function adds 5 to the input
function add5(x) {
    return x + 5
}

map(add5, 4); // returns 9

Using lambda functions

Lambda functions are quite useful when it comes to higher-order functions because they allow to shorten expressions. Let's rewrite the map function example above with lambda functions:

const map = (func, val) => func(val);

const add5 = x => x + 5;

map(add5, 4); // returns 9

If there is a particular function that is only ever going to be called once during the program execution, then there is no need to assign the function a name. These are called anonymous functions and can use lambda function notation.

Rewriting the above example using an anonymous function:

// assume we have map, but add5 is only going to be used once
map(x => x + 5, 4); // returns 9

Lambda expressions work very well when it comes to declaring anonymous functions (functions that are only used once in the entire code) and using them for higher-order function evaluation. When an anonymous function needs to have multiple lines, then anonymous lambda expressions can still be used but may look cluttered.

Next steps

Next, we'll take a look at strings in JavaScript and some string methods.

Last updated