Functions in JavaScript: Secrets You Haven't Heard Of

What Every Professional JavaScript Programmer Should Know

Hello, Habr! We invite future students of the course "JavaScript Developer. Professional" to take part in an open webinar on the topic "Making an interactive Telegram bot on NodeJs" .

We also share the traditional translation of a useful article.


Every programmer can write functions. They are often referred to as first class objects because they are a key JavaScript concept. But do you know how to use them effectively?

Today I will give some tips for advanced functions. Hope you find them useful. The article contains several sections:

  • Pure functions

  • Higher order functions

  • Function caching

  • Lazy functions

  • Currying

  • Function composition

Pure functions

What is a pure function?

A function is said to be pure if both of the following conditions are met:

  • ;

  • .

1

function circleArea(radius){
  return radius * radius * 3.14
}

, . , . .

2

let counter = (function(){
  let initValue = 0
  return function(){
    initValue++;
    return initValue
  }
})()



- , .

3

let femaleCounter = 0;
let maleCounter = 0;
function isMale(user){
  if(user.sex = 'man'){
    maleCounter++;
    return true
  }
  return false
}

isMale , , . maleCounter, .

?

? . , .

1. , .

. .

2. .

.

for (int i = 0; i < 1000; i++){
    console.log(fun(10));
}

fun , fun(10) 1000 .

fun , . , , .

let result = fun(10)
for (int i = 0; i < 1000; i++){
    console.log(result);
}

3. .

. assert , .

. 1.

const incrementNumbers = function(numbers){
  // ...
}

:

let list = [1, 2, 3, 4, 5];
assert.equals(incrementNumbers(list), [2, 3, 4, 5, 6])

, , .

?

:

  • ;

  • .

, .

, . , , .

:

const arr1 = [1, 2, 3];
const arr2 = [];
for (let i = 0; i < arr1.length; i++) {
    arr2.push(arr1[i] * 2);
}

JavaScript map().

map(callback) , .

const arr1 = [1, 2, 3];
const arr2 = arr1.map(function(item) {
  return item * 2;
});
console.log(arr2);

map โ€” .

, . .

, :

function computed(str) {    
    // Suppose the calculation in the funtion is very time consuming        
    console.log('2000s have passed')
      
    // Suppose it is the result of the function
    return 'a result'
}

, , . ?

cached . , , , . cached , Object Map.

function cached(fn){
  // Create an object to store the results returned after each function execution.
  const cache = Object.create(null);

  // Returns the wrapped function
  return function cachedFn (str) {

    // If the cache is not hit, the function will be executed
    if ( !cache[str] ) {
        let result = fn(str);

        // Store the result of the function execution in the cache
        cache[str] = result;
    }

    return cache[str]
  }
}

:

, .

, ยซยป , . .

, foo, Date, .

let fooFirstExecutedDate = null;
function foo() {
    if ( fooFirstExecutedDate != null) {
      return fooFirstExecutedDate;
    } else {
      fooFirstExecutedDate = new Date()
      return fooFirstExecutedDate;
    }
}

. , . - .

:

var foo = function() {
    var t = new Date();
    foo = function() {
        return t;
    };
    return foo();
}

.  โ€” .

.

DOM - , IE. :

function addEvent (type, el, fn) {
    if (window.addEventListener) {
        el.addEventListener(type, fn, false);
    }
    else if(window.attachEvent){
        el.attachEvent('on' + type, fn);
    }
}

addEvent . , :

function addEvent (type, el, fn) {
  if (window.addEventListener) {
      addEvent = function (type, el, fn) {
          el.addEventListener(type, fn, false);
      }
  } else if(window.attachEvent){
      addEvent = function (type, el, fn) {
          el.attachEvent('on' + type, fn);
      }
  }
  addEvent(type, el, fn)
}

, , , , . , .

 โ€” .

, , , ; โ€” , .

?

  • .

  • . .

  • .

add. .

function add(a,b,c){
 return a + b + c;
}

( ) , , ( ).

add(1,2,3) --> 6 
add(1,2) --> NaN
add(1,2,3,4) --> 6 //Extra parameters will be ignored.

?

:

function curry(fn) {
    if (fn.length <= 1) return fn;
    const generator = (...args) => {
        if (fn.length === args.length) {

            return fn(...args)
        } else {
            return (...args2) => {

                return generator(...args, ...args2)
            }
        }
    }
    return generator
}

:

, , :

bitfish, HELLO, BITFISH

, :

  • ;

  • .

:

let toUpperCase = function(x) { return x.toUpperCase(); };
let hello = function(x) { return 'HELLO, ' + x; };
let greet = function(x){
    return hello(toUpperCase(x));
};

, (greet) . , greet : fn3(fn2(fn1(fn0(x)))).

compose, :

let compose = function(f,g) {
    return function(x) {
        return f(g(x));
    };
};

, greet compose:

let greet = compose(hello, toUpperCase);
greet('kevin');

compose , , .

compose , , .

underscore compose .

function compose() {
    var args = arguments;
    var start = args.length - 1;
    return function() {
        var i = start;
        var result = args[start].apply(this, arguments);
        while (i--) result = args[i].call(this, result);
        return result;
    };
};

, , .


- "JavaScript Developer. Professional".

- " Telegram NodeJs" .




All Articles