Functions
About 473 wordsAbout 6 min
2025-08-05
This page explores functions beyond basic declarations, covering context, scope, and advanced patterns that are central to the language.
Function Declarations, Expressions, and IIFEs
Declarations vs. Expressions:
- Declaration:
function myFunction() {}
. They are fully hoisted, meaning they can be called before they are defined in the code. - Expression:
const myFunction = function() {};
. The variable (myFunction
) is hoisted, but the function assignment is not (if usinglet
/const
, it's in the TDZ). This encourages a top-down code structure.
Immediately Invoked Function Expressions (IIFE): An IIFE is a function that is defined and executed immediately. It's a classic pattern for creating a private scope to avoid polluting the global namespace.
(function() {
// All variables and functions here are private
const message = "This is private";
console.log(message);
})(); // The final () invokes the function
A Deep Dive into the this
Keyword
The value of this
is one of the most confusing parts of JavaScript. It is determined by how a function is called, following four main rules of precedence:
new
Binding (Highest Precedence): When a function is called with thenew
keyword (a constructor call),this
is a brand-new object created for that call.- Explicit Binding: Using
.call(thisArg, ...args)
,.apply(thisArg, argsArray)
, or.bind(thisArg)
, you can force a function to use a specific object forthis
..bind()
returns a new function withthis
permanently bound. - Implicit Binding: When a function is called as a method on an object (
obj.myMethod()
),this
is the object (obj
). - Default Binding (Lowest Precedence): If none of the other rules apply,
this
defaults to the global object (window
in browsers) orundefined
in'use strict'
mode.
Arrow Functions and Lexical this
: Arrow functions (=>
) are an exception. They do not have their own this
context. Instead, they lexically inherit this
from their surrounding code. This makes them predictable and ideal for callbacks where you want to preserve the context of the outer method.
- Mastering Closures for Practical Use A closure is the combination of a function and the lexical environment within which that function was declared. This means the inner function has access to the variables of its outer function, even after the outer function has finished executing.
Practical Use Case: Memoization (Caching) Closures are perfect for creating functions that cache their results.
function memoize(fn) {
const cache = {}; // This cache is private to the closure
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) {
console.log("Fetching from cache...");
return cache[key];
}
console.log("Calculating result...");
const result = fn(...args);
cache[key] = result;
return result;
};
}
const slowSquare = (n) => {
// Simulate a slow operation
for(let i=0; i<1e7; i++) {}
return n * n;
};
const fastSquare = memoize(slowSquare);
fastSquare(5); // "Calculating result..."
fastSquare(5); // "Fetching from cache..."
Changelog
2aa48
-web-deploy(Auto): Update base URL for web-pages branchon
Copyright
Copyright Ownership:WARREN Y.F. LONG
License under:Attribution-NonCommercial-NoDerivatives 4.0 International (CC-BY-NC-ND-4.0)