JavaScript Functions: Explained for Beginners

A function is a set of statements designed to perform a particular task.

Functions are usually referenced by a name, and when this is the case, the set of statements can be reused or executed as many times as needed in a program. It is a way to run the same statements from multiple places in a program without having to rewrite them each time they are needed.

Functions are one of the fundamental building blocks in JavaScript and you’ll find them useful when you need to repeatedly perform an action throughout your program.

This tutorial addresses the following touchpoints:

  • How to define functions in JavaScript
  • Function declarations and function expressions
  • Return values
  • How to invoke JavaScript functions

JavaScript allows us to define functions in different ways. A common way to do this is through the function keyword. Let's write a function that multiplies any number by two and returns its new value:

function multiplyByTwo(value) {
    if (isNaN(value)) {
      return 'Value must be a number'
    }
    return (value * 2)
}

From our above function;

  • The function name is provided right after the function keyword.
  • The parenthesis right after the function name holds the function parameters.
  • Parameters are names used to represent real values that are provided when a function is invoked.

The return statement is used to end the execution of a function while returning a specified value. This means that, as defined in the condition, if the value is not a number, the first return statement would terminate the function and return the string, 'Value must be a number'.

The above method we used to define our JavaScript function is called function declaration. To invoke our function, we only need to write its name followed by a parenthesis.

multiplyByTwo()

Remember that in our function definition, we used the parameter, value to represent the real value to be multiplied. To provide our value to be multiplied, we'll place it right inside the parenthesis in our function call.

console.log(multiplyByTwo(35))
// 70
console.log(multiplyByTwo('any non-number'))
// 'Value must be a number'

The values we supplied to our function are called arguments.

During a function definition, the names that represent the values we intend to supply to the function are called parameters.

During a function call, the actual values provided to the function are called arguments.

We can pass in up to 255 parameters in a function definition.

Without using the return statement to tell our function what to return, its default value would be undefined. Let's test this by creating a function without a return statement, and then invoking it:

function multiplyByTwo(value) {
    value*2
}

console.log(multiplyByTwo(35))
// undefined

The function also returns undefined by default when the return keyword is provided without a value. This makes it an empty return:

function multiplyByTwo() {
    value * 2
    return
}

console.log(multiplyByTwo(35))
// undefined

While function declarations allow us to define named functions, they also allow us to define anonymous functions and Immediately Invoked Function Expressions (IIFE).

Anonymous functions are functions that are without names, hence, the word anonymous.

function () {
    return alert("I'm a function, and I'm anonymous!")
}

Since our above function cannot be referenced by a name, there is no way to call it elsewhere in our codebase. When this is the case, the function is usually an IIFE (Immediately Invoked Function Expression). This means that it'll be invoked immediately after it is declared. To achieve this, we'll place a parenthesis right after the function declaration.

(function () {
    return alert("I'm a function, and I'm anonymous!")
})()

Notice how we declared our function inside the parenthesis before invoking it.

To be able to reuse an anonymous function, it has to be assigned to a variable. In this way, it can be referenced by that variable name. A way to do this is through Function expression. Let's assign our anonymous function to a variable.

const alertUser = function() {
    return alert("I'm anonymous and can be referenced by a name!")
}

Now, we can invoke (or call) our function the same way we invoked multiplyByTwo. Since our function has no parameter, there'll be no need to supply an argument.

alertUser()

Important things to note

When returning an expression in a function, don't add a newline between return and the value.

You might be tempted to separate your expression from the return statement like this:

function reverseWord(word) {
    return
        word.split("").reverse().join("")
}

console.log(reverseWord("inevitable"))
// undefined

This returns undefined because our compiler ends the statement by assuming a semicolon after the return keyword, making it an empty return:

function reverseWord(word) {
    return;
        word.split("").reverse().join("")
}

If you want to wrap the return statement across multiple lines, you should start your expression on the same line as the return keyword, or have an opening parenthesis on the same line as the return keyword:

function reverseWord(word) {
    return (
        word.split("").reverse().join("")
    )
}

console.log(reverseWord("inevitable"))
// "elbativeni"

Or

function reverseWord(word) {
    return word.split("")
        .reverse().join("")
}

console.log(reverseWord("inevitable"))
// "elbativeni"

....

A function name should be descriptive, straight to the point and timeless.

Notice how we named our first function multiplyByTwo. This is because its job is to actually multiply a number by two. Doing this would help anyone know what our function does by just looking at its name.

Function naming is a very important part of function definition and choosing to disregard this would make your code non-readable, non-maintainable and would further lead to reduced efficiency.

When naming your functions, it is important to not use slangs that only a few people would understand or trends that people can only relate to at a given time. Let your function names be descriptive enough, straight to the point and timeless.

....

A function should have only one responsibility.

When you define your function, let it have just one responsibility and do only what its name suggests. This means that from our examples, choosing to reverse a word and multiply a number in the same function would not be a good idea. Like we did, it is better to split the two actions into separate functions.

By doing this, you would not only make your code more readable, but you'll also make it easier to test and debug.

Summary

  • A function is a set of statements designed to perform a particular task.
  • During a function definition, the names that represent the values we intend to supply to the function are called parameters.
  • During a function call, the actual values provided to the function are called arguments.
  • We can pass in up to 255 parameters in a function definition.
  • An anonymous function is a function that has no name, and to be able to reuse an anonymous function, it has to be assigned to a variable.
  • An IIFE (Immediately Invoked Function Expression) is a function that is invoked immediately after it is declared.
  • A function should have only one responsibility.
  • Function names should be descriptive, straight to the point and timeless.

Thanks for reading! If you still need this further simplified, no worries; here's a link to The Simplest Explanation of Functions You’ll Ever Read.

Found this helpful? Please drop an emoji 💓, comment 📝, and share! 🎷

Comments (4)

Add a comment
Fábio Miranda's photo

Great article. The article is interesting even for those who are not beginners , because many developers only use but not understanding really the technology.

Ebenezer Don's photo

Full-stack Software Engineer

Thanks Fábio Miranda! I'm really glad you found this helpful.

Klaus Ferreira's photo

Wow! Great article! I had to bookmark it. Thanks for sharing :)

Ebenezer Don's photo

Full-stack Software Engineer

Thanks Klaus Ferreira! I'm really glad you found this helpful.