functions in javascript
Functions in JavaScript
First-class citizens, declaration types, arrow functions, and parameter semantics.
The Universal Artisan Worker
Because functions are first-class objects in JS, they can be stored in data structures, passed as parameters, and returned from higher-order functions. This power enables Functional Programming patterns.
Function Declarations vs Expressions
Declarations (`function foo() {}`) are hoisted with their body. Expressions (`const foo = function() {}`) behave as variable assignments and are only callable after assignment.
Arrow Functions (ES6)
Arrow functions provide concise syntax and lexical `this` binding (they inherit `this` from their outer scope). They lack their own `this`, `arguments`, `super`, and `new.target`.
First-Class and Higher-Order Functions
A Higher-Order Function (HOD) is any function that either accepts another function as an argument, returns a function, or both (e.g., `map`, `filter`, `compose`).
Rest Parameters vs arguments Object
Modern ES6 rest parameters (`(...args) => {}`) provide a real Array instance. The legacy `arguments` object is array-like but lacks array methods like `map` or `slice`.
First-class function capabilities and arrow function lexical this:
// Higher-Order Function returning a specialized function
function createMultiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log(double(10)); // 20
console.log(triple(10)); // 30
// Arrow function lexical this demonstration
const team = {
name: "Frontend Guild",
members: ["Alice", "Bob"],
printMembers() {
// Arrow function inherits 'this' from printMembers (team object)
this.members.forEach(member => {
console.log(`${member} is in ${this.name}`);
});
}
};
team.printMembers();
20
30
Alice is in Frontend Guild
Bob is in Frontend Guild
Using Arrow Functions as Object Methods
The Risk: `const obj = { val: 42, getVal: () => this.val }; obj.getVal();` returns `undefined` because arrow function resolves `this` to the outer global/module scope.
The Fix: Use shorthand method syntax `getVal() { return this.val; }` for object methods requiring instance `this`.
- ✓ First-Class Citizens: Functions can be stored, passed, and returned like any value.
- ✓ Arrow functions have lexical `this` (no dynamic binding) and cannot be used as constructors (`new`).
- ✓ Prefer rest parameters `(...args)` over legacy `arguments` object.
- ✓ Higher-Order Functions accept or return other functions.
- ✓ Default parameters evaluate at call time, not definition time.