Functions Deep Dive
Functions are first-class citizens in JavaScript — they can be assigned to variables, passed as arguments, and returned from other functions. This is the foundation of functional programming patterns heavily tested in interviews.
Function Declaration vs Expression
// Declaration — hoisted fully
function add(a, b) { return a + b; }
// Expression — hoisted as undefined
const subtract = function(a, b) { return a - b; };
// Arrow function (ES6)
const multiply = (a, b) => a * b;
Arrow Functions vs Regular Functions
Key difference: Arrow functions do NOT have their own this, arguments, or prototype.
const obj = {
value: 42,
regular: function() { return this.value; }, // 42
arrow: () => this.value // undefined (or window.value)
};
IIFE (Immediately Invoked Function Expression)
(function() {
const secret = 'hidden';
console.log('Runs immediately!');
})();
// secret is not accessible here
Used to create private scope, avoiding global pollution — classic interview topic.
Higher-Order Functions
A function that takes another function as argument or returns a function.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2); // [2,4,6,8,10]
const evens = numbers.filter(n => n % 2 === 0); // [2,4]
const sum = numbers.reduce((acc, n) => acc + n, 0); // 15