JavaScript functions: What they are and how to use them

Since the earliest computer programmers wrote the first programs, functions have been essential to software development. Sometimes referred to as procedures or subroutines, functions are fundamental building blocks of code that can be reused across a program. They give developers the power to abstract away complexity, organize code into easily reusable programs, and break complicated logic up into easier manageable blocks. In no uncertain terms, organizing and maintaining code would require superhuman abilities without functions.

Unsurprisingly, functions are core to most programming languages, and JavaScript is no different. Even though it began as a much humbler and far less capable programming language for browsers, it now powers countless websites, desktop and mobile applications, and server-side tools, making it the most widely used language in the world. And to be sure, developers could write functions in JavaScript from the very beginning. 

In this guide, you’ll take a deep dive into JavaScript functions and explore how they work and why they’re so useful for complex applications and software. Additionally, you'll discover some useful approaches and learn how to write JavaScript functions so you can take advantage of them in your own projects.

What is a JavaScript function?

Practically speaking, a JavaScript function is described as a reusable block of code that performs a specific task. This task might be performing a calculation or processing business logic, which may also require passing arguments into the function and receiving a return value, but neither are hard requirements. Finally, the statements that make up a function go within a code block called the function body. 

While there are nuances and exceptions, JavaScript code is generally interpreted line by line, from top to bottom, unless a statement tells the interpreter to do something differently, such as processing a loop or conditional. This process and the order the interpreter follows is called control flow. Like other code blacks, when the JavaScript interpreter encounters a function call, it steps into the functions and processes the code. Once it's complete, the interpreter steps back out of the function and resumes its normal flow. 

Functions can be called as many times as needed within the scope they’re defined. Writing and using a function is a little like writing and using a specialized program within code. Once a developer creates a function, they can use it repeatedly within the scope of their code. Moreover, when developers need to update a function, whether to address bugs or add functionality, they only need to update the original definition. 

Another benefit of writing functions is that it gives developers the ability to better organize their codebases. If they need to write code that covers specific business logic more than once, they can define it as a function, effectively abstracting it away. This reduces complexity, making it easier for developers to focus on code that needs working on.

JavaScript functions as objects

In JavaScript, functions are first-class objects. This means that they can be passed to other functions as arguments or returned as values. They can also be assigned to variables. As objects, functions are special containers with distinct properties. One of the properties of an object is called a method, which is essentially a function that's defined in an object. 

This simple function demonstrates the concept:

    function helloPlanet(planet) { return "Hello, " + planet + " ! " ; } ;
let helloWorld = helloPlanet("world") ;
console.log(helloWorld) ;

Our example includes a helloPlanet() function that defines a single parameter called planet and returns a concatenated string. Below the function, the helloWorld variable is declared and initialized with the helloPlanet function. In the function, the string "world" is passed in as an argument. Finally, the helloWorld variable is logged to the console with console.log.

This is a convoluted way of printing “Hello, world!” to the console, but it demonstrates a few key concepts regarding functions and objects, including parameters, return values, variable assignment, and passing functions to other functions. Likewise, console.log demonstrates objects and their methods — specifically the log method within the console object

Some examples of useful JavaScript functions

With the basics out of the way, one of the best ways to learn how to interact with and learn JavaScript functions is by looking at the ones that are built into the language. It's also good to know what's available so you don't waste time reinventing any wheels. Below are only a few of JavaScript's built-in functions.

The parseInt() function

The parseInt() function is used to convert a string with numbers in it to the data type of integer. It accepts two arguments: the starting string and an optional radix for specifying the mathematical numeral system. It’s worth mentioning that, while the radix is optional, the numeral system used is inferred based on the number, so don’t assume every result will use base-10

To explain how it works, let's assume there's a street address stored as a string in some code, but you need to retrieve the street number as an integer. Here is what the code would look like to do so:

    let address = "1024 Megabyte Lane" ;
let addressStreetNumber = parseInt(address, 10) ;

Despite how it appears at first glance, parseInt() doesn’t return every integer within a string. Rather, it parses the string until it reaches a non-number character, and then it stops.

For example, if the string assigned to the address variable started with a character other than a number, parseInt() would return NaN, which is JavaScript language for “Not a Number.” On the other hand, if the address had an apartment number following the street name, the result would still be 1024.

The isNaN() function

When working with numbers and arithmetic, you can use the isNaN() function to determine whether a value is an illegal number. If the function returns true, the value is an illegal number; otherwise, the number is valid. 

One use case for isNaN() is verifying that numerical operations were successful, such as in the previous example with parseInt(). This function is also useful for verifying the result of a mathematical expression. 

Take the following code, for example:

    let factor = 1.17 ;
let variance = 100 ;
let angle = 4073.48 * factor / variance isNaN(angle) ;

Because the mathematical operation is valid in this example, isNaN() would return true, indicating the value of the angle was a valid number. But let’s assume there’s a bug in the code that resets the factor and variance variables to 0. Because the math operation results in an indeterminate form, the isNaN() function would return true.

The Math.random() method

Like other programming languages, JavaScript has a robust set of built-in mathematical operations, which are accessed from the Math object. One of the most versatile of these is the Math.random() method, which returns a pseudorandom floating-point number between 0 and 1. 

Practically speaking, the ability to generate a random number is infinitely useful in computer science, with applications ranging from statistics to simulations to video games. This makes Math.random() a method you’ll reach for many times. 

To generate a random number from 0 up to but not including 1, simply assign the function to a variable like so:

    let randomNumber = Math.random( ) ;

If you need a random number within a specified range, you can create variables and use arithmetic to modify the results: 

    let min = 20; let max = 70; let x = Math.random()  * (max - min) + min ;

Keep in mind that the numbers generated with Math.random() rely on a relatively weak pseudorandom number generator. While it’s useful in many ways, it shouldn’t be used in applications with sensitive data or in software that requires high levels of security.

The encodeURI() function

The encodeURI() function encodes a uniform resource indicator, or URI, for use as part of a uniform resource locator, or URL. It accomplishes this by replacing certain characters within the URI with the corresponding escape codes that represent each character’s UTF-8 encoding.

For example:

    let path = "/Directories With/Spaces & Other Symbols/Aren't Conventional" ;
let encodedPath = encodeURI(path) ;
console.log(encodedPath) ;

This code would print the following string to the console:

    "/Directories%20With/Spaces%20&%20Other%20Symbols/Aren't%20Conventional "

Spaces, ampersands, and apostrophes aren’t valid characters in URLs, but they are valid for directory and file names. If you’re developing an app that accesses system files via HTTP, encodeURI() will replace the invalid characters with the proper escape codes so that your app can find the appropriate resources.

JavaScript function syntax

As you might have noticed earlier, one way to define a function in JavaScript is with the function keyword, which is called a function declaration. A function's name comes after the function keyword, and it adheres to the same naming conventions as variables. The parentheses following the name are used to define parameters. Finally, an opening curly brace followed by a line break is the beginning of the body of the function, and it’s where a function's logic is defined.

Here’s what a barebones function declaration looks like:

    function myFunctionName(parameter) {
// code
} ;

Another approach for defining a function is called a function expression, which uses a variable declaration with a function definition assigned to it. On the left side of the operator, function expressions look like typical variables. To the right of the operator is the function keyword followed by parentheses, including parameters, and then the body of the function wrapped in curly braces.

The syntax for a function expression is:

    const myFunctionName = function(parameter) {
// code
} ;

Finally, the arrow function syntax, which was added with ES6, is the most concise way of defining functions in JavaScript. Like a function expression, arrow functions are defined using the var, const, or let keywords, followed by the function name and the assignment operator. To the right of the operator, the function keyword is dropped and => is added between the closing parenthesis and the opening curly bracket.

Here’s an example of an arrow function:

    const myFunctionName = (parameter) => {
// code
} ;

There are a few considerations that determine which syntax to write your functions in, though these are more advanced concepts, such as the execution context, the keyword, and the creation of objects. Because of these factors, it’s best to use the more verbose function declaration until you’re more acquainted with JavaScript’s nuances.

How to call a JavaScript function

By now, you probably have a hunch on how to call a function in JavaScript. Essentially, once a function is defined, it’s called by writing the function name followed by parentheses and any arguments required by the function’s parameters. 

For example, the function below takes a number as an argument and returns the square root:

    function squareRoot(number) {
return number * number;
} ;

Calling or invoking the function requires only the name and a number passed in as an argument. This can be called independently, within another function or code block, or assigned to a variable:


// This function invocation returns 16

if (squareRoot(4) > 15) {
return "Over"
} else {
return "Under"

// This if statement returns "Over" 

let squareRootOf32 = squareRoot(32); 

// This variable returns 1024

Why use JavaScript functions

In JavaScript and every other language, functions are fundamental. More importantly, they provide a number of benefits that make a developer's life easier. In this regard, functions are one of the most versatile and valuable ways to write code. By understanding the advantages clearly, developers can lean into them and, in turn, write better and more efficient code and improve their programming experience. 

Functions can make your code more readable

Writing functions gives you the opportunity to break complex logic down into smaller, more manageable parts. This helps provide both organization and clarity to your code. It also reduces complexity. In addition to better organizing your codebase, writing functions make things far more readable and understandable — both for you and other contributors. 

This higher readability helps promote reuse and maintainability. Later, when you need to revisit a function to add new capabilities or simply review it, you'll find that the individual functions that you organized and wrote according to the task they performed are much easier to read and understand. 

Functions can save you time

The DRY principle of good programming asserts a simple adage: Don't repeat yourself. Writing functions helps you adhere to this assertion. Writing custom statements to address repetitive tasks is a time sink, especially when it's faster and easier to call a function. If you start programming the same functionality a second time, go back to the first instance and break it out into a function. In doing so, you'll save yourself countless programming hours. 

Functions can help you avoid mistakes

Complex codebases with several hundreds or thousands of statements make debugging inherently difficult. By organizing their codebases into functions, developers inherently refine the code they write, refactoring it into specialized blocks that serve a singular purpose. In turn, they can more easily spot errors during the process. Additionally, writing functions makes hunting down bugs much simpler. If a bug rears its head on a task associated with a specific function, it significantly reduces the amount of code where the bug could be hiding. 

How to write your own JavaScript function

With a solid foundation in JavaScript functions, it’s time to build something on your own. You can use a JavaScript file on your computer, a runtime like Node.js, or an online code playground like JSFiddle. The first step is to define the function using the function keyword and function declaration syntax

    function myFunctionName(parameter) {
// your code goes here

Next, add the JavaScript statements within the curly braces. Your function’s body can include variables, loops, conditionals, and other functions:

    function myFunctionName(yourFirstName) {
return "Hey " + yourFirstName + ", great job writing your first function!" ;
} ;

To call the function, simply invoke it by writing the name of the function followed by parentheses containing the parameters you defined:

    myFunctionName("John") ;

Functions: JavaScript’s fundamental building blocks

As one of JavaScript’s fundamental building blocks, the ability to write great functions is foundational to software engineering. Because the syntax used for functions in JavaScript never changes, the fundamentals covered in this guide give every learner the tools they need to write code that’s more readable, reusable, and maintainable. And as they explore new projects and collaborate with other developers, they'll discover techniques for writing efficient and better organized functions. 

Though the syntax is fixed, those new to programming will eventually encounter an abundance of abstract ideas around function use and code organization. There's plenty more to study for anyone seeking to improve their skills. Those who enjoy writing functions might find functional programming fascinating, which is a paradigm that emphasizes function use in code. For those who are more interested in learning the skills of a full-stack engineer, studying recursion, scope, and closure in JavaScript are excellent next steps.

Capital One Tech

Stories and ideas on development from the people who build it at Capital One.

Related Content