» Quick Introduction to JavaScript » 1. Basics » 1.7 Functions

Functions

Generally speaking, a function is a "subprogram" that can be called by code external to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function as parameters, and the function will return a value.

In JavaScript, the Function object provides methods for functions. Every function is actually a Function object.

// Normal function declaration
function addNumbers(a, b) {
  return a + b;
}

// Normal function expression
const multiplyNumbers = function(a, b) {
  return a * b;
};

// Using the normal function
console.log(addNumbers(5, 3));        // Output: 8
console.log(multiplyNumbers(2, 4));   // Output: 8

Since ES6, you can also do arrow functions.

// Arrow function expression with explicit return
const divideNumbers = (a, b) => {
  if (b !== 0) {
    return a / b;
  } else {
    return 'Cannot divide by zero';
  }
};

// Arrow function expression
const subtractNumbers = (a, b) => a - b;

// Using the arrow functions
console.log(subtractNumbers(8, 3));   // Output: 5
console.log(divideNumbers(10, 2));    // Output: 5
console.log(divideNumbers(7, 0));     // Output: 'Cannot divide by zero'

Function Parameters

A parameter is a named variable passed into a function. Parameter variables are used to import arguments into functions.

JavaScript doesn't care how many parameters you pass in. The extra parameters will be ignored, and the missing ones get assigned 'undefined'.

function f(a, b) {
    console.log(a, b);
}

f("hello", 123, "there");
// hello 123

f("hello");
// hello undefined

You can also have default parameters.

function f(a, b = "world") {
    console.log(a, b);
}

f("hello");
// hello world

IIFE

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog.

(function() {
    var x = 10;
    console.log(x); // Output: 10
})();

The function is defined within parentheses and immediately invoked with the () at the end. The variables declared inside the function are scoped to the function and won't interfere with variables outside of it.

Closures

A closure is the combination of a function bundled together with references to its surrounding state. In other words, a closure gives you access to an outer function's scope from an inner function.

function makeFunc() {
  const name = "literank";
  // This function has access to `name`
  // because it closes over outer variables
  function displayName() {
    console.log(name);
  }
  return displayName;
}

const myFunc = makeFunc();
myFunc(); // literank

Higher Order Functions

In JavaScript, a higher-order function is a function that can take other functions as arguments or return functions as results. This concept is a fundamental part of functional programming.

Function as an Argument

// Higher-order function that takes a function as an argument
function doOperation(operation, a, b) {
    return operation(a, b);
}

// Functions to pass as arguments
function add(x, y) {
    return x + y;
}

function subtract(x, y) {
    return x - y;
}

// Using the higher-order function
console.log(doOperation(add, 5, 3));      // Output: 8
console.log(doOperation(subtract, 5, 3)); // Output: 2

Function as a Return Value

// Higher-order function that returns a function
function multiplier(factor) {
    return function (number) {
        return number * factor;
    };
}

// Creating specific multiplier functions
var double = multiplier(2);
var triple = multiplier(3);

// Using the returned functions
console.log(double(4)); // Output: 8
console.log(triple(5)); // Output: 15

Array Higher-Order Functions

// Higher-order function - Array.map()
var numbers = [1, 2, 3, 4, 5];
var squaredNumbers = numbers.map(function (num) {
    return num * num;
});
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

// Higher-order function - Array.filter()
var evenNumbers = numbers.filter(function (num) {
    return num % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4]

Code Challenge

Write a function called filterArray that takes an array of numbers as input and returns a new array containing only the even numbers. Use a higher-order function such as filter to accomplish this.

Loading...
> code result goes here
Prev
Next