Home > Articles

Functions and Functional Programming in JavaScript

  • Print
  • + Share This

JavaScript has an object model that is very different from class-based programming languages. Learn about functions and functional programming, which is very important in JavaScript.

Save 35% off the list price* of the related book or multi-format eBook (EPUB + MOBI + PDF) with discount code ARTICLE.
* See informit.com/terms

This chapter is from the book

This chapter is from the book


In this chapter, you will learn how to write functions in JavaScript. JavaScript is a “functional” programming language. Functions are “first-class” values, just like numbers or strings. Functions can consume and produce other functions. Mastering a functional programming style is essential for working with modern JavaScript.

This chapter also covers the JavaScript parameter passing and scope rules, as well as the details of throwing and catching exceptions.

3.1 Declaring Functions

In JavaScript, you declare a function by providing

  1. The name of the function

  2. The names of the parameters

  3. The body of the function, which computes and returns the function result

You do not specify the types of the function parameters or result. Here is an example:

function average(x, y) {
  return (x + y) / 2

The return statement yields the value that the function returns.

To call this function, simply pass the desired arguments:

let result = average(6, 7) // result is set to 6.5

What if you pass something other than a number? Whatever happens, happens. For example:

result = average('6', '7') // result is set to 33.5

When you pass strings, the + in the function body concatenates them. The resulting string '67' is converted to a number before the division by 2.

That looks rather casual to a Java, C#, or C++ programmer who is used to compile-time type checking. Indeed, if you mess up argument types, you only find out when something strange happens at runtime. On the flip side, you can write functions that work with arguments of multiple types, which can be convenient.

The return statement returns immediately, abandoning the remainder of the function. Consider this example—an indexOf function that computes the index of a value in an array:

function indexOf(arr, value) {
  for (let i in arr) {
    if (arr[i] === value) return i
  return -1

As soon as a match is found, the index is returned and the function terminates.

A function may choose not to specify a return value. If the function body exits without a return statement, or a return keyword isn’t followed by an expression, the function returns the undefined value. This usually happens when a function is solely called for a side effect.

  • + Share This
  • 🔖 Save To Your Account