Skip to content

Latest commit

 

History

History
101 lines (74 loc) · 2.58 KB

File metadata and controls

101 lines (74 loc) · 2.58 KB

First Class Functions & Anonymous Functions

First-Class Functions in JavaScript

Definition: In JavaScript, functions are first-class citizens, meaning they are treated like any other value.

Implications:

Functions can be:

  • Assigned to variables
  • Passed as arguments to other functions
  • Returned from other functions
  • Stored in data structures (arrays, objects, etc.)

Example:

// 1. Assigning to a variable
const greet = function (name) {
  return `Hello, ${name}`;
};

// 2. Passing as an argument
function sayHello(fn) {
  console.log(fn('JS'));
}
sayHello(greet);

// 3. Returning from a function
function multiplier(x) {
  return function (y) {
    return x * y;
  };
}
const double = multiplier(2);
console.log(double(5)); // 10

Interview Soundbite: "First-class functions mean functions can be used as values — assigned, passed, and returned — giving JavaScript its functional programming power."

Anonymous Functions

Definition: An anonymous function is a function without a name in its declaration.

Key Points:

  • Often used when functions are assigned to variables, passed as arguments, or used in IIFEs.
  • Cannot be referenced by name in recursion unless stored in a variable.
  • Improves brevity but can make debugging harder (stack traces may lack function names).

Example:

// Anonymous function assigned to a variable
const greetUser = function (name) {
  return `Hello, ${name}`;
};

// Anonymous function as a callback
setTimeout(function () {
  console.log('Timer done!');
}, 1000);

First-Class Functions + Anonymous Functions Together

This is where interviewers connect the dots:

  • Anonymous functions are often used because JavaScript treats functions as first-class.
  • Without first-class function behavior, passing anonymous functions as arguments wouldn't be possible.

Example:

function processUserInput(callback) {
  const name = 'JavaScript';
  callback(name);
}

// Passing an anonymous function as an argument
processUserInput(function (user) {
  console.log(`Welcome, ${user}`);
});

Bonus — Named Function Expressions

You can name the function even when assigning to a variable — helps debugging.

const greetUser = function greetFn(name) {
  console.log(`Hello, ${name}`);
};

Interview Soundbite: "JavaScript supports first-class functions, so they can be treated like variables — assigned, passed, and returned. Anonymous functions are simply functions without names, commonly used as values for first-class functions, especially in callbacks and IIFEs."