String Methods
These help you process, clean up, and change text safely.
A function is simply a reusable piece of behavior. Instead of writing the same logic again and again, you write it once and just call it whenever you need it. This makes your code easier to test, easier to maintain, and safer to build on later.
In JavaScript, functions are treated as first-class values. This simply means a function can be stored inside a variable, passed into another function, or even returned out of a function. This one idea is the foundation behind callbacks, event handlers, asynchronous code, and functional programming patterns.
When a function is called, JavaScript creates a brand new execution context just for that call. The parameters get set up, local variables are created, and each line runs one after another, in order. If a return statement is reached, the function stops right there, and that value is sent back to wherever the function was called from.
function greet(name) { return "Hello " + name;}Function declarations are hoisted along with their entire function body. This means you can actually call greet() before the line where it is written in your code, and JavaScript will still be able to find it.
const greet = function(name) { return "Hello " + name;};Function expressions are created while the code is running, and then stored inside a variable. The variable name itself might get hoisted, but the actual function is not available until the line where it is assigned. This style is common when you want to treat a function like a piece of data.
const greet = (name) => "Hello " + name;Arrow functions give you a shorter way to write functions, and they use something called lexical this. This means they borrow this from the place where they are written, instead of creating their own. They are especially handy for callbacks and short, simple transformations.
sayHi("Ava");
function sayHi(name) { return `Hi, ${name}`;}This style works best when you want named, reusable functions that are easy to read and easy to debug.
const sayHi = function(name) { return `Hi, ${name}`;};This style works best when you want to treat functions like values and pass them around your code.
const sayHi = (name) => `Hi, ${name}`;This style works best for short callbacks, and for places where you want lexical this.
function add(a, b) { // parameters return a + b;}
add(2, 3); // argumentsParameters are just placeholder names written inside the function definition. Arguments are the actual values you pass in when you call the function. Giving parameters clear, meaningful names makes your code easier to read and helps avoid mistakes.
function greet(name = "Guest") { return "Hello " + name;}Default parameters are used whenever an argument turns out to be undefined. They save you from writing repetitive checks, and they make it clear what your function expects.
function sum(...numbers) { return numbers.reduce((acc, val) => acc + val, 0);}Rest parameters let you gather multiple values into a single array. Use this when you do not know in advance how many values will be passed in.
function square(x) { return x * x;}return immediately stops the function and sends a value back to wherever it was called from. If you do not write a return yourself, JavaScript automatically returns undefined.
A closure happens when an inner function keeps access to variables from its outer function, even after that outer function has already finished running.
Closures are very important for keeping private state, for memoization (caching results), for building function factories, and for many patterns used in asynchronous code.
function outer() { let count = 0;
return function inner() { count++; return count; };}
const counter = outer();counter(); // 1counter(); // 2The variable count is still available because inner “remembers” the surrounding environment where count was originally created, even though outer has already finished running.
An IIFE is a function expression that runs right away, immediately after it is defined. It used to be very common before modern modules existed, mainly to keep variables isolated and avoid messing up the global scope.
(function () { console.log("IIFE executed");})();(function (name) { console.log("Hello " + name);})("Sahil");In modern JavaScript, ES modules already give you scope at the file level, so IIFEs are not used as often anymore. Still, it helps to understand them, since you will run into them in older code and in interview-style examples.
A higher-order function is one that either takes one or more functions as input, returns a function as output, or does both. This lets you write more general, reusable logic and plug in different behavior as needed.
function greet(fn) { fn();}
greet(() => console.log("Hello"));Many built-in methods, such as map, filter, reduce, and find, are actually higher-order functions.
Getting good with built-in methods is what helps you move from writing code that simply works, to writing code that is clean and easy to follow. The goal here is not to memorize every single method, but to understand what each group of methods is good for, and when to reach for it.
String Methods
These help you process, clean up, and change text safely.
Array Methods
These let you loop through, transform, search, and combine collections of data.
Number Methods
These help you format numbers for display and check whether number values are valid.
Object Methods
These let you look at keys, values, and entries, and help you build updates without changing the original object.
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", "", ""]String methods are useful for cleaning up text before you validate it or compare it. For example, usernames and tags are often turned to lowercase and trimmed of extra spaces before they get saved.
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 when you want to transform every item, filter when you want to pick out certain items, find when you only want the first match, and reduce when you want to combine everything down into a single 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 handy for formatting how numbers are displayed, and for safely checking input that comes from users or from an API.
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 you look inside data structures, and let you build a new, updated version of an object without changing (mutating) the original one.
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 important for working with timestamps, while JSON methods are needed whenever you send structured data across the network, like to or from a server.
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 brand new array with transformed values. Use forEach when you just need to do something on the side, like 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 gives you back only the very first match. filter gives you back every single item that matches.
const arr2 = [10, 20, 30, 40];
arr2.slice(1, 3); // [20, 30], original unchangedarr2.splice(1, 2); // removes [20, 30], original mutatedIt is usually better to use slice when you want the original array to stay untouched.
[1, 2, 3].map((x) => { x * 2;});The callback above does not actually return anything, so the result ends up being [undefined, undefined, undefined].
[1, 2, 3].map((x) => x * 2);Start with one data type at a time. Learn around 5 to 7 core methods for that type, and practice them again and again.
Build method chains gradually. Write just one transformation per line before you start combining several operations together.
Track mutation vs immutability. Always be aware of whether a method changes the original data or not.
Use meaningful callback names. Giving good names reduces logic mistakes when working with higher-order functions.
Validate edge cases. Test things like empty arrays, missing values, and unexpected types of input.