Skip to main content

Function declarations

1) Function declaration

javascript
function sum(a, b) { return a + b; }
  • hoisting (can be called before declaration).
  • Has its own this when called as a method/function.
  • Can be used as a constructor (new sum()).

2) Function expression

javascript
const mul = function(a, b) { return a * b; };
  • No hoisting (available after assignment).
  • Can be anonymous or named:
javascript
const fact = function factorial(n) { /* ... */ }; // named - the name is available inside the function

3) Arrow function

javascript
const inc = x => x + 1; const sum = (a, b) => a + b;
  • Lexical this - this is taken from the surrounding lexical scope.
  • No arguments (rest ...args can be used instead).
  • Cannot be used as a constructor (new), no prototype.
  • Great for callbacks and short functions.

4) Function constructor

javascript
const fn = new Function('a', 'b', 'return a + b');
  • Creates a function from a string (like eval).
  • Not recommended: security and performance concerns.

5) Generator function (function*)

javascript
function* idGenerator() { let i = 0; while (true) { yield i++; } }
  • Returns an iterator; supports yield.
  • Execution can be paused/resumed.

6) Async function

javascript
async function fetchData() { const r = await fetch('/api'); return r.json(); } const fn = async () => { /* also possible */ };
  • Returns a Promise.
  • await can be used inside.

7) Method definitions in objects (shorthand)

javascript
const obj = { sayHi() { console.log('hi'); }, // method async load() { await fetch('/'); } // async method };
  • Convenient for methods; they have [[HomeObject]] - support for super.
  • Can also be written as prop: function() {} - this is a regular function expression.

8) Class methods (inside class)

javascript
class C { method() {} static staticMethod() {} async asyncMethod() {} }
  • Class methods - no hoisting, used with instances/the class, support super.

9) IIFE - Immediately Invoked Function Expression

javascript
(function() { // runs immediately })();
  • Useful for local scope (previously - before modules).

10) Function.prototype.bind (creating a bound function)

javascript
function f() { console.log(this); } const bound = f.bind({x:1});
  • Returns a new function with a fixed this and/or partially applied arguments.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.