Intro to Functions in Javascript.

What are functions?

Celestino Salim
Oct 9, 2018 · 4 min read

Functions are “self contained” modules of code that accomplish a specific task. Functions usually “take in” data, process it, and “return” a result. Once a function is written, it can be used over and over and over again. Functions can be “called” from the inside of other functions.

Defining Functions in Javascript

In order to use functions we have to define them, the syntax may vary but most of the time, it will follow this structure:

  • The function keyword
  • A function name
  • A list of parameters
  • A block statement {}
  • An explicit return.
function helloWorld(parameters) {
return (parameters);
}
helloWorld("Hello, World!")

This syntax is known as a function declaration, it can be invoked before it is defined because of hoisting. We’re not going to dig deeper into Hoisting, but it is important to know that it’s JavaScript’s default behavior of moving declarations to the top.

Another syntax that we can use to define a function is function Expressions. Notice that in function declaration, the function has a name (helloWorld), while function expressions can be named or anonymous and they’re not hoisted. This means that they cannot be used before defining.

const helloWorld = function(parameters) {
return (parameters);
}
helloWorld("Hello, World!")

And Arrow Function Expression is a shorter syntax for writing function expressions.

const helloWorld = (parameters) => parametershelloWorld("Hello, World!")

Function types in Javascript.

Based on the above we can split functions into 3 different types.

  • Named function

A named function is defined and then can be called when we need it by referencing its name and passing arguments to it.

  • Anonymous function

An anonymous function needs to be tied to something such as a variable or an event, in order to run.

  • Immediately invoked function expression(IIFE).

An IIFE will run as soon as the browser finds it.

In JavaScript, functions are first-class objects. One of the consequences of this is that functions can be passed as arguments to other functions and can also be returned by other functions.

A function that takes other functions as arguments or returns functions as its result is called a higher-order function, and the function that is passed as an argument is called a callback function.

Higher-order functions & Callbacks.

A good example of higher-order functions & callbacks is the built ins .filter &.map methods.

Filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true.

const drivers = [
{ name: 'Sally', revenue: 400 },
{ name: 'Annette', revenue: 200 },
{ name: 'Jim', revenue: 150 }];
function driversWithRevenueOver(drivers, revenue) {
return drivers.filter(function(driver) {
return driver.revenue > revenue
})
}
function driverNamesWithRevenueOver(drivers, revenue) {
return driversWithRevenueOver(drivers,revenue).map(function(driver){ return driver.name })}

The example above have a function called driverNamesWithRevenueOver that returns a function this is what we call higher-order function and the .map function(driver) is the callback function.

Nested Functions

A function can be nested, which means we can define a function inside another function and return it.

function outer(){
function inner(){
return "Hello World!";
}
return inner;
}
outer()()

Closures

A closure is an inner function made accessible from outside of its parent function with in-scope variables and their values incorporated from the environment in which it was created. In that environment, it has access to its own local variables, to its outer function’s variables and the global variables (declared outside its outer function).

function phrase(name) {
const hello = "Hello";

function printPhrase() {
console.log(hello + " " + name);
}

printPhrase();
}

phrase("Gavin");

In this code example, the printPhrase() function refers to the name variable and the hello parameter of the enclosing (parent) phrase()function. And the result is that, when phrase() is called, printPhrase() successfully uses the variables and parameters of the former to output:

Hello Gavin
undefined

Pure Functions & Impure Functions.

Pure Functions

  1. Always returns the same result if the same arguments are passed in. It does not depend on any state, or data, change during a program’s execution. It must only depend on its input arguments.
  2. The function does not produce any observable side effects such as network requests, input and output devices, or data mutation.
function calculateSquareArea(x) {
return x * x;
}

Impure functions

This is an impure function because it depends on an external tax variable. A pure function can not depend on outside variables.

const tax = 0.8function calculateTax(productPrice) {
return (productPrice * (tax/100));
}

The benefits of using pure functions is they are immediately testable. They will always produce the same result if you pass in the same arguments.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade