What is a Function?

This guide will help you understand the concepts of Javascript functions and their structure.



What is a Function
Image by Editor

 

The very first high-level functional programming, LISP, was developed in the 1950s. It introduced concepts that we still use in programming today. For instance, Lambda functions and expressions. Even object-oriented languages such as JAVA and C# have borrowed notations and features from functional programming languages.    

While LISP still exists today as a family of different programming languages, none of them are as popular as JavaScript or Python - which are generally used as functional programming languages (among their other paradigms). And as the label suggests, functional programming languages revolve around functions. 

But what is a function and how is it different from a method? Since JavaScript is the most popular programming language globally (at least at the time of this guide’s inception), we’ll use it as an example. Ultimately, the concepts you will learn here are transferable to other programming languages that follow a functional paradigm.

 

The Nature of JavaScript and why Functions Matter

 

Despite introducing classes in the ECMAScript 2015 specification (ES6), JavaScript still isn’t considered a class-based object-oriented language. That’s largely because you don’t have to define classes or class files to build a JavaScript project. You can define and call functions outside the context of classes. 

In fact, before the release of the ECMAScript 2015 specification, JavaScript functions followed simple but loose rules. Thus, they were straightforward to use compared to functions (or methods) in OO programming languages like C# and JAVA. As the last few annual ECMAScript specifications brought more functionality to JavaScript, they also made the language far more complex.              

Regardless, JavaScript still stands as the most widely used programming language in the world due to its extensibility and portability. You can use it for client-side web development and server-side and desktop applications when paired with the right runtime and frameworks.   

We can only see JavaScript adoption increase in the future as more cloud-database platforms (DBaaS) have begun to offer native JavaScript SDKs. Thus, programmers are no longer restricted to using SQL drivers for MSSQL and MySQL or their associated libraries and functions.

JavaScript is worth learning and mastering – now more than ever. Functions make JavaScript tick, and your usage of them will determine the ultimate quality of your code and projects. But the behavior and structures of functions (especially Lambda/Arrow functions) can be difficult to grasp for beginners. 

The syntax can be particularly off-putting when JavaScript code is embedded in HTML. Nevertheless, if you hope to progress from a beginner to an expert, you must be able to construct and utilize functions effectively. And the first step is answering the question: “What are functions?”

 

What are Functions?

 

JavaScript functions are a set of instructions contained in a labeled code block. They’re important because they allow you to refer to these sets of instructions using a label instead of repeatedly writing them out every time. A call or invocation describes the process of using or referring to a function in your code. 

As a functional programming language, JavaScript has what is known as first-class functions. This means that functions can be treated as objects or first-class citizens. They can be passed through the arguments of other functions, included in data structures, and assigned to variables/objects. While this adds some extensibility to JavaScript, it can make code harder to read and follow. Regardless, its functional nature is what makes it suitable for data science. The basic structure of a function declaration is as follows:

function nameOfFunction(Parameter1, Paramater2, …) {
    //Body of function
}

 

Here’s a simple function that returns the sum of two variables:

function add(v1, v2) {
    return v1 + v2;
}

 

The function is defined using the “function” keyword followed by the name of the function (the signature), a parameter list separated by commas and placed between round parentheses, and a code block. Unlike, (older versions) of C# and Java, you don’t have to specify a return type when defining your function. This also speaks to JavaScript’s loosely typed nature.

The function’s name/label can be a combination of alphanumeric characters, underscores (_), and dollar signs ($). You can invoke the above function to assign a value to a variable/attribute like so:

let out_put = add(5, 5);

      

The values in between the rounded parentheses in an invocation are called arguments. Not all JavaScript functions are defined or declared by the programmer.    

JavaScript has a set of built-in functions for essential tasks such as manipulating strings and arrays, working with HTML wrappers, handling dates, etc. JavaScript’s standard library isn’t as rich or fully featured as most General-Purpose Programming Languages (GPL). This can be advantageous as it lowers the learning curve and streamlines coding as you don’t have to worry about using the right object or data type.

Again, if you’re familiar with OO programming languages, you may be slightly confused. You may have noticed that JavaScript functions are structured and behave similarly to methods. But is there a distinction between methods and functions, and does JavaScript have methods? 

 

Functions vs. Methods

 

Methods and functions are synonymous in many programming languages. However, JavaScript defines these terms differently; thus, functions and methods are two slightly different concepts. The differences are minor because they have identical structures and similar usages but are defined and called from different contexts.

Methods are object functions as they are constructed as part of an object’s property list. The main difference between functions and methods is that methods are tied to specific objects, while functions are not. Essentially, the property list (including methods) gives objects class-like functionality. The syntax of JavaScript methods is as follows:

ObjectDefinition = {
    methodLabel: function [KEYWORD]() {
        //The method’s body
    }
};

 

Here’s a simple example of a method that returns the sum of two numbers:

var addition = {
    firstNumber: 1,
    secondNumber: 5,

    summate: function() {
        return this.firstNumber + this.secondNumber;
    }
};

 

The “this” keyword is used to prevent variable shadowing/hiding, ultimately helping you control and maintain scope. You use it to reference other properties within the scope of the object’s declaration. 

You can call the method by using the object like so:

addition.summate();

 

Function Expressions (Anonymous Functions)

 

As mentioned previously, you can store functions in variables or properties. Function expressions allow you to declare anonymous functions that assign their return values to variables. As you’ll see, they’re quite similar to object methods. The basic syntax of a function expression is as follows:

[VARIABLE DECLARATION KEYWORDS: var |
    const |
    let
] variableName = function([PARAMETER LIST]) {
    //Body of function
}

 

A simple example of a function expression is as follows:

var summate = function(firstNumber, secondNumber) {
	return firstNumber + secondNumber;
}

 

You can then call the function using the variable label:

summate(1,5);

 

Arrow Functions

 

Arrow functions were first introduced in the ECMAScript 2015 standard (ES6). They’re akin to Lambda expressions in Python and C# as they allow you to create more concise declarations and function calls (and they both use arrows). However, they can be a little tricky to use at first. The basic syntax of an arrow function is:

[let |
    const |
    var
] functionName = ([PARAMETER LIST…]) => expression[The Body of The Function]

 

When put into action, it looks like this:

[let |
    const |
    var
] functionName = ([PARAMETER LIST…]) => {
    //The Body of The Function]
}

 

Or like this:

var summate = (firstNumber, secondNumber) => firstNumber + secondNumber;

 

You can also anonymize arrow expressions by negating the function signature like so:

 (firstNumber, secondNumber) => firstNumber + secondNumber;

 

Another advantage of arrow functions is how they handle the “this” keyword and scoping. If a normal function is defined outside the scope of an object, it refers to the object that invokes it. In a web browser environment, this could be a button, window, document, etc. Contrastingly, when “this” is used with arrow functions, it always references the object in which it is declared/defined.

 

Summary

 

One of the most compelling reasons why JavaScript is beloved is its flexibility, although some surmise that tighter constraints and rules may simplify the coding experience. 

Because of its multi-paradigm nature, it embraces various coding styles, as evidenced by how it allows you to declare and use functions. This looseness makes it easier for developers to obfuscate their code somewhat naturally, so they don’t have to restrict themselves to a particular style of function. 

As a beginner, if you’re not comfortable with using arrow functions yet, stick to simple declarations and calls. How fast you master a skill or language is highly dependent on your understanding of the basics.

 
 
Nahla Davies is a software developer and tech writer. Before devoting her work full time to technical writing, she managed — among other intriguing things — to serve as a lead programmer at an Inc. 5,000 experiential branding organization whose clients include Samsung, Time Warner, Netflix, and Sony.