String Methods
Process, clean, and transform text safely.
Functions are reusable units of behavior. Instead of writing the same logic repeatedly, you define it once and call it whenever needed. This makes code easier to test, easier to maintain, and safer to extend.
In JavaScript, functions are first-class values. This means a function can be stored in a variable, passed to another function, or returned from a function. This single property is the foundation of callbacks, event handlers, asynchronous code, and functional programming patterns.
When a function is called, JavaScript creates a fresh execution context. Parameters are initialized, local variables are allocated, and statements run in order. If a return statement is reached, execution stops immediately and the returned value is sent back to the caller.
function greet(name) { return "Hello " + name;}Function declarations are hoisted with their full function body. That means you can call greet() before the line where it is declared in source code, and JavaScript will still find it.
const greet = function(name) { return "Hello " + name;};Function expressions are created at runtime and assigned to a variable. The variable may be hoisted, but the function value is not available until assignment happens. This style is common when passing a function as data.
const greet = (name) => "Hello " + name;Arrow functions provide concise syntax and lexical this, which means they inherit this from their surrounding scope instead of creating their own. They are especially useful for callbacks and short transformations.
sayHi("Ava");
function sayHi(name) { return `Hi, ${name}`;}Best when you want named, reusable functions that are easy to read and debug.
const sayHi = function(name) { return `Hi, ${name}`;};Best when functions are treated as values and passed around.
const sayHi = (name) => `Hi, ${name}`;Best for short callbacks and places where lexical this is desired.
function add(a, b) { // parameters return a + b;}
add(2, 3); // argumentsParameters are placeholders in the function definition. Arguments are actual values passed during a function call. Clear naming for parameters improves readability and reduces bugs.
function greet(name = "Guest") { return "Hello " + name;}Default parameters are used when an argument is undefined. They prevent repetitive guard logic and make API contracts explicit.
function sum(...numbers) { return numbers.reduce((acc, val) => acc + val, 0);}Rest parameters collect multiple values into an array. Use this when the number of inputs is not fixed.
function square(x) { return x * x;}return ends function execution immediately and sends a value back to the caller. If no explicit return is provided, JavaScript returns undefined.
A closure appears when an inner function keeps access to variables from its outer function even after the outer function has finished execution.
Closures are essential for private state, memoization, function factories, and many asynchronous patterns.
function outer() { let count = 0;
return function inner() { count++; return count; };}
const counter = outer();counter(); // 1counter(); // 2The variable count remains available because inner closed over the lexical environment where count was created.
An IIFE is a function expression that executes immediately after being defined. It was heavily used before modern modules to isolate variables and avoid polluting global scope.
(function () { console.log("IIFE executed");})();(function (name) { console.log("Hello " + name);})("Sahil");In modern JavaScript, ES modules already provide file-level scope, so IIFEs are less common. Still, understanding them helps you read older code and interview-level examples.
A higher-order function takes one or more functions as arguments, returns a function, or both. This lets you build generic logic and inject behavior.
function greet(fn) { fn();}
greet(() => console.log("Hello"));Many built-in methods such as map, filter, reduce, and find are higher-order functions.
Method mastery is how you move from writing correct code to writing expressive code. The goal is not to memorize every method, but to understand what each category solves and when to choose it.
String Methods
Process, clean, and transform text safely.
Array Methods
Iterate, transform, search, and aggregate collections.
Number Methods
Format numeric output and validate number values.
Object Methods
Inspect keys, values, entries, and build immutable updates.
const str = " JavaScript Patterns ";
str.trim(); // "JavaScript Patterns"str.toUpperCase(); // " JAVASCRIPT PATTERNS "str.includes("Script"); // truestr.slice(2, 12); // "JavaScript"str.replace("Patterns", "Methods"); // " JavaScript Methods "str.split(" "); // ["", "", "JavaScript", "Patterns", "", ""]Use string methods for normalization before validation and comparison. For example, usernames and tags are often lowercased and trimmed before storing.
const arr = [1, 2, 3, 4, 5];
arr.map((x) => x * 2); // [2, 4, 6, 8, 10]arr.filter((x) => x % 2 === 0); // [2, 4]arr.find((x) => x > 3); // 4arr.some((x) => x > 4); // truearr.every((x) => x > 0); // truearr.reduce((acc, x) => acc + x, 0); // 15Use map for transformation, filter for selection, find for first match, and reduce for aggregation into one value.
const n = 1234.567;
n.toFixed(2); // "1234.57"n.toPrecision(5); // "1234.6"Number.isInteger(n); // falseNumber.isNaN(Number("abc")); // trueNumber.parseInt("42px", 10); // 42Number.parseFloat("3.14rem"); // 3.14Number methods are useful for display formatting and defensive checks around user input or API payloads.
const user = { id: 1, name: "Sahil", active: true };
Object.keys(user); // ["id", "name", "active"]Object.values(user); // [1, "Sahil", true]Object.entries(user); // [["id", 1], ["name", "Sahil"], ["active", true]]
const copy = Object.assign({}, user, { active: false });// { id: 1, name: "Sahil", active: false }Object methods help inspect data structures and construct immutable updates without mutating original references.
const now = new Date();now.toISOString();now.getFullYear();
const payload = { name: "Ana", score: 99 };const json = JSON.stringify(payload);const parsed = JSON.parse(json);Date methods are essential for timestamps, while JSON methods are required when sending structured data across network boundaries.
const nums = [1, 2, 3];
const mapped = nums.map((n) => n * 2); // returns new arrayconst result = nums.forEach((n) => n * 2); // returns undefinedUse map when you need a transformed array. Use forEach for side effects such as logging.
const users = [ { id: 1, role: "user" }, { id: 2, role: "admin" }, { id: 3, role: "admin" }];
users.find((u) => u.role === "admin");users.filter((u) => u.role === "admin");find returns the first match. filter returns all matching items.
const arr2 = [10, 20, 30, 40];
arr2.slice(1, 3); // [20, 30], original unchangedarr2.splice(1, 2); // removes [20, 30], original mutatedPrefer slice when you want non-mutating behavior.
[1, 2, 3].map((x) => { x * 2;});The callback above does not return a value, so the result becomes [undefined, undefined, undefined].
[1, 2, 3].map((x) => x * 2);Start with one data type at a time. Learn 5 to 7 core methods for that type and practice them repeatedly.
Build method chains gradually. Write one transformation per line before combining operations.
Track mutation vs immutability. Always know whether a method changes original data.
Use meaningful callback names. Better names reduce logic mistakes in higher-order functions.
Validate edge cases. Test empty arrays, missing values, and unexpected input types.