JavaScript the Fun Part



Some type of functions in JavaScript you may already know.

1. Regular function

Pretty straight forward why of using a function.

First we declare the function.

Then we invoke it.

2. Method

A function that is assigned as a property of an object.

The object that gets assignment can call that function.

So first declaration in scope of an object.

Then invocation using an object.

3. Constructor

If we declare a function and then call it using new keyword, then the function acts as a constructor for us.

Thus first declaration.

Then invocation using new keyword.

4. Function expression

This kind of function relates to functional languages that treats function as a first class object.

In the style we treat a function as a value or date and store it in a variable, or passing it around e.g as a argument for another function.

So it is kind of first declaration and then passing or assigning.

// function expression, assignment
const add = function( x ,y ){ return x + y; }
const sub = function( x, y ){ return x - y; }

const addAndSub = function( _add, _sub, x, y ){
    const a = _add( x, y );
    const s = _sub( x, y );
    return [ a, s ];

// function expression passing it around
const r = addAndSub( add, sub, 10, 5 ); // Array [ 15, 5 ]

5. Named function expression

A function expression that has name. This name is useful for:

// function expression that has name
const sum = function _sum( first, second, ){
    if( !rest.length ) return first + second;
    return _sum( first + second, );

sum( 1, 1, 1, 1, 1, 0, 1 ); // 6

// it is not accessible outside
_sum( 1, 2, 3 ); // ReferenceError: _sum is not defined

Update: Thu Sep 05 2019 19:20:17 GMT+0430 (Iran Daylight Time)