Javascript functions are an important part of the Javascript standard. They allow you to create reusable blocks of code with specific names and behaviors so you don’t have to repeat the same thing multiple times, which is extremely helpful for code readability and maintenance.

Basics of Javascript Functions

Javascript functions always start with the reserved word “function,” followed by the function name. Parameters to the function, in parentheses, follow the function name. Finally, the code block associated with the function name must appear after the parentheses.

function exampleFunction(param1, param2) {
... instructions ...
}

Function names can include alphanumeric characters (A-Z, a-z, and 0-9), underscores, and dollar signs. These are the same naming requirements Javascript uses for variables.

When Javascript encounters a function definition, it associates a function’s code block with its name. A Javascript program does not execute the instructions within a function’s code block unless explicitly told to do so, a process called invocation.

Invoking the function above, assuming two arguments that are both integers (whole numbers), would look like this:

exampleFunction(1, 2);

Functions can return a value to a Javascript program with a specific line of code called a return statement, which specifies a value after the reserved word “return.” A return statement prevents the rest of the function from being executed.

function exampleFunction(param1, param2) {
    ... instructions ...
    return true;
}

A return statement isn’t required inside a function, but it’s common for programmers to put complex instructions inside a function so they can return a computed value without repeating code. Any variables defined inside a function, known as local variables, exist only within that function, so complicated processes remain isolated.

You can set the value of a variable with a value returned from a function. Never try to set a variable’s value from a function that doesn’t have a return statement.

let myVariable = exampleFunction(1, 2);

Organizing Code with Javascript Functions

Javascript doesn’t require you to write code in functions, but functions make complex code easier to maintain and reuse. Anything more than a trivial program with a few lines could likely benefit from having code in functions.

Unlike many other programming languages, Javascript allows you to declare functions within functions. An inside function doesn’t affect code outside of its outer function, but an outer function can call the inner function as many times as necessary.

function outer {
    function inner() {
        ... instructions ...
    }
    ... instructions ...
    inner();
    ... more instructions ...
}

When one function is wrapped inside another, the resulting code structure is called a “closure.” Closures are a way for Javascript to create semi-private variables and functions that the rest of a program shouldn’t access.

There are no hard rules for what should go into a function and what should not. Different programmers might organize the same lines of code into very different functions, or not organize them into functions at all.

The point of functions and closures is to make code as readable, maintainable, and efficient as possible. Splitting complex code into functions that are reused a lot could be helpful, for example, while splitting simple code into many functions could create so much extra work while calling the functions that the code performance would suffer.

Best Practices for Writing Javascript Functions

Short and Descriptive Names

When writing Javascript functions, keep function names as short and descriptive as possible. A short, descriptive name helps in maintenance and debugging because it’s easy to tell what a function does at a glance.

Out of the following function names, the third name is the most useful because it is both short and descriptive. It’s often tempting to create a long function name so you can be as descriptive as possible, but context clues in the surrounding code often mean that you don’t need to worry about creating long names.

fe();
FusionEnergyOutputInMegaElectronVolts();
fusionEnergy();

If you’re ever worried that a function name might be ambiguous, you can always add comments near the function definition that you can refer to later. Sometimes, you don’t need a lot of detail in a function name to get the point of the function across.

// deuterium+tritium=helium | 1H2 + 2He3 = 1p1 + 2He4 (+ 18.3 MeV)
// https://personal.ems.psu.edu/~radovic/Chapter14.pdf
fusionEnergy();

Specific Function Behaviors

A general rule when writing functions is to make sure that every function does one specific thing. This doesn’t mean that every line of code needs a different function; instead, make sure that everything in a function is unique and clearly defined.

For example, when creating a program that makes numeric calculations, you wouldn’t want to have a function that has two complex calculations like the Fibonacci sequence and a factorial in one code block. It would be better to have a separate function for each calculation, then call them from a third function if necessary:

function factorial(val) {
    ... instructions ...
}

function fibonacci(num1, num2) {
    ... instructions ...
}

function basics(num1, num2) {
    factorial(num1 + num2);
    fibonacci(num1, num2);
}

Structuring the code this way makes it clear which parts of the code are performing different calculations. If you want to reuse the calculations in other places, all you have to do is call the separate functions.

Conclusion

Javascript functions help developers keep code organized for easy maintenance and debugging. Planning functions well can minimize duplication of code while making a program easy to understand.

Enroll in our Intro to Programming Nanodegree Program today to learn more about Javascript functions and other programming concepts.

Start Learning