Functions

Types

function foo(args) {...} - function declaration

  • semicolon shouldn't be used at the end of function declaration


const foo = function() {...} - function expression

  • returns reference to this function
  • named function expression (NFE) - function with additional name. NFE is mostly used for recursion
  • e.g. const foo = function bar() { ... }; - "bar" name is only accessible within "foo" function


(foo, bar) => foo + bar - arrow function

  • returns reference to this function
  • curly braces can be omitted in arrow function. in such case function body should contain single expression, which is function's return value
  • "this" inside arrow function is object from closure
  • "this" in arrow function, which is object method, also takes "this" from closure instead of referring to object
  • arrow function doesn't have "arguments"
  • arrow function is forbidden being a constructor, it doesn't have prototype


const foo = new Function(arg1, argN, functionBody) - some analog of eval()

  • functionBody - any instruction
  • [[Environment]] references to global lexical environment instead of parent

Useful

parameter - variable in a function definition that acts as a placeholder for the value that the function will receive
argument - the actual value passed to the function when it is called

default parameter - can be used for the case when parameter is expected, but not passed

  • e.g. function foo(bar = '') { ... }


arguments - variable, which contains collection with all arguments passed to the function

self-invoking function - a function that calls itself

  • can be used for variable scoping
  • function declaration can't be self-invoking
(const foo = () => {
  console.log('hello');
})();

first-class function - concept, when function is treated like any other variable, i.e. function can be assigned to variable, passed as an argument or returned

  • callback - function which is passed as argument into another function


higher-order function - function which accepts callback function as an argument and/or returns other function

  • this is also called wrapper function


function object - each function is an object. it can have static properties and methods

  • default properties are:
  • name - contains function name
  • length - amount of parameters function takes. rest parameters are not counted

Closure

closure - function with all the outside variables which are available for it

  • closure exists because function remembers lexical environment of the place where function literal was written
  • closure can be used to save data. i.e. special wrapper accepts data as an argument and returns function. argument will be accessible in return function
function createCounter() {
  let count = 0;

  return function () {
    return count++;
  };
}

const counter1 = createCounter();
const counter2 = createCounter();

counter1(); // 0
counter1(); // 1
counter2(); // 0

decorator - higher-order function that returns a function which enhances the function received as an argument without modifying it

  • debounce is a popular example of decorator
  • decorators can be used to implement caching for CPU-heavy functions
function playDecorator(play) {
  return function (...args) {
    return play(...args) + haveFun();
  }
}

const playTennisAndHaveFun = playDecorator(playTennis)

playTennisAndHaveFun(bro1, bro2, rackets, ball);

Global Functions

setTimeout(callback, delay?, arg1?, argN?) - allows running a function after the interval of time

  • delay - default is 1 millisecond
  • arg1, argN - will be passed into callback function
  • timerId - value, returned by setTimeout. timerId is accessible from callback
  • clearTimeout(timerId) - cancel the execution


setInterval(callback, delay, arg1?, argN?) - allows running a function repeatedly, starting after the interval of time

  • callback doesn't run immediately, it runs after first delay
  • clearInterval(timerId) - stop the execution


alert() - is used to show output
prompt() - is used to get user input

  • these two functions work synchronously


postMessage() - enables cross-origin communication between window objects. e.g. page & pop-up that it spawned; page & iframe embedded within it

  • incoming messages fire "message" event. event object contains origin, which should be validated
  • targetWindowElement.contentWindow.postMessage(message, targetOrigin) - a way to send message inside
  • targetOrigin - where to send
  • * - send everywhere. postMessage XSS should be considered
  • window.parent.postMessage() - send message outside
;