JavaScript Function

Photo by Luca Bravo on Unsplash

JavaScript Function

learn on what functions are, types, and how to use them in JavaScript.

Functions are the basis of JavaScript or the fundamental building block in JavaScript. A set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.

Types of functions in JavaScript

1. Function declarations

A function definition also called a function declaration, or function statement consists of the keyword function , followed by:

  • The name of the function.
  • A list of parameters to the function, enclosed in parentheses and separated by commas.
  • The JavaScript statements that define the function, enclosed in curly brackets, {...}. example;
// function declaration
function square(number) {
  return number * number;
}

2. A regular function

The function declaration matches for cases when a regular function is needed. Regular means that you declare the function once and later invoke it in many different places. This is the basic scenario:

function sum(a, b) {
  return a + b;
}
sum(5, 6);           // => 11
([3, 7]).reduce(sum) // => 10

3. Function expression

A function expression is very similar to and has almost the same syntax as a function declaration. The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions.

// function expression
const getRectArea = function(width, height) {
  return width * height;
};

console.log(getRectArea(3, 4));
// expected output: 12

Difference from function expression

It is easy to confuse the function declaration and function expression. They look very similar but produce functions with different properties.

An easy to remember rule: the function declaration in a statement always starts with the keyword function.

// Function expression: starts with "const"
const isTruthy = function(value) {
  return !!value;
};
// Function expression: an argument for .filter()
const numbers = ([1, false, 5]).filter(function(item) {
  return typeof item === 'number';
});
// Function expression (IIFE): starts with "("
(function messageFunction(message) {
  return message + ' World!';
})('Hello');

4. Shorthand method definition

Shorthand method definition can be used in a method declaration on object literals and ES2015 classes. You can define them using a function name, followed by a list of parameters in a pair of parenthesis (para1, ..., paramN) and a pair of curly braces { ... } that delimits the body statements.

const obj = {
  foo() {
    return 'bar';
  }
};

console.log(obj.foo());
// expected output: "bar"

5. Arrow function

An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations. There are differences between arrow functions and traditional functions, as well as some limitations:

  • Arrow functions don't have their own bindings to this or super, and should not be used as methods.
  • Arrow functions don't have access to the new.target keyword.
  • Arrow functions aren't suitable for call, apply and bind methods, which generally rely on establishing a scope.
  • Arrow functions cannot be used as constructors.
  • Arrow functions cannot use yield, within its body.
// Traditional Anonymous Function
function (a, b){
  let chuck = 42;
  return a + b + chuck;
}

// Arrow Function
(a, b) => {
  let chuck = 42;
  return a + b + chuck;
}

6. Generator function

When called, generator functions do not initially execute their code. Instead, they return a special type of iterator, called a Generator. When a value is consumed by calling the generator's next method, the Generator function executes until it encounters the yield keyword.

function* makeRangeIterator(start = 0, end = 100, step = 1) {
    let iterationCount = 0;
    for (let i = start; i < end; i += step) {
        iterationCount++;
        yield i;
    }
    return iterationCount;
}

7. new Function/ new Operator

The new keyword does the following things:

  1. Creates a blank, plain JavaScript object.
  2. Adds a property to the new object (proto) that links to the constructor function's prototype object.
  3. Binds the newly created object instance as the this context (i.e. all references to this in the constructor function now refer to the object created in the first step).
  4. Returns this if the function doesn't return an object.
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

const car1 = new Car('Eagle', 'Talon TSi', 1993);

console.log(car1.make);
// expected output: "Eagle"

Thanks for reading!, hope you learnt somethin new?