JavaScript Functions Guide

javascript
functions
closures
async

Function Types

Function Declaration

  • Hoisted: Can be called before the declaration.
function add(a, b) {
  return a + b;
}
console.log(add(2, 3)); // 5

Function Expression

  • Not hoisted: Cannot be used before the declaration.
const subtract = function (a, b) {
  return a - b;
};
console.log(subtract(5, 3)); // 2

Arrow Function

  • Shorter syntax, no this context.
const multiply = (a, b) => a * b;
console.log(multiply(4, 3)); // 12

Advanced Concepts

Closures

  • Functions that "remember" the variables in their scope.
function outer() {
  let count = 0;
  return function inner() {
    count++;
    return count;
  };
}
const increment = outer();
console.log(increment()); // 1
console.log(increment()); // 2

Async Functions

  • Return promises, allow await for asynchronous code.
async function fetchData() {
  const response = await fetch('https://api.example.com');
  return response.json();
}