JavaScript how-to
Short ready-made solutions to common JavaScript tasks with code examples.
Strings
- How to capitalize the first letter of a stringCapitalizing the first letter of a string in JavaScript: toUpperCase and slice, a helper function and every word.
- How to check if a string contains a substringChecking for a substring in JavaScript: includes, case-insensitive search and finding the position.
- How to check if a string is emptyChecking for an empty string in JavaScript: length, a string of spaces, null and undefined.
- How to check if a string starts or ends with a substringChecking the beginning and the end of a string in JavaScript: startsWith, endsWith, ignoring case and several variants.
- How to compare strings ignoring caseComparing strings in JavaScript without regard to case: toLowerCase and localeCompare with sensitivity.
- How to convert a string to an arraySplitting a string into an array in JavaScript: by a separator, by characters and by words.
- How to convert camelCase to snake_case and backConverting between camelCase, snake_case and kebab-case in JavaScript with replace and a regular expression.
- How to count characters in a stringCounting characters in JavaScript: length, emoji and other special symbols, and the number of a specific character.
- How to count words in a stringCounting words in JavaScript: split by spaces, extra spaces and the most frequent word.
- How to create a URL slug from a stringTurning a title into a URL slug in JavaScript: lowercase, hyphens instead of spaces, removing accents and extra characters.
- How to escape HTML in a stringEscaping special HTML characters in JavaScript so that user text is shown as text and not as markup.
- How to extract numbers from a stringGetting numbers out of text in JavaScript: match with a regular expression, decimal numbers and keeping only digits.
- How to find the position of a substringFinding where a substring is in JavaScript: indexOf, lastIndexOf, all positions and search with a regular expression.
- How to generate a random stringA random string in JavaScript: from a set of characters, with Math.random and with crypto for codes and tokens.
- How to hide part of a stringMasking a card number, a phone or an email in JavaScript with stars: slice, padStart and repeat.
- How to pad a number with leading zerosLeading zeros in JavaScript with padStart: numbers, hours and minutes.
- How to remove all spaces from a stringRemoving whitespace in JavaScript: all spaces, tabs and line breaks, and collapsing repeated spaces into one.
- How to remove HTML tags from a stringGetting plain text from HTML in JavaScript: a regular expression and DOMParser in the browser.
- How to replace text in a stringReplacing a substring in JavaScript: replaceAll, replace and case-insensitive replacement.
- How to reverse a stringReversing a string in JavaScript with split, reverse and join, including strings with emoji.
- How to split text into linesSplitting a multi-line string in JavaScript: split by line breaks, Windows line endings and empty lines.
- How to trim whitespace from a stringRemoving whitespace in JavaScript: trim, trimStart, trimEnd and collapsing repeated spaces.
- How to truncate a string to a given lengthTruncating a long string in JavaScript and adding an ellipsis with slice.
Arrays
- How to calculate the average of an arrayThe arithmetic mean of an array in JavaScript: reduce and length, an empty array and the average of an object field.
- How to check if a value exists in an arrayChecking for a value in a JavaScript array: includes for primitives and some for objects.
- How to check if all array elements match a conditionChecking array elements in JavaScript: every for all elements, some for at least one, and an empty array.
- How to compare two arraysComparing arrays in JavaScript: element by element with every, ignoring order and why === does not work.
- How to convert an array to a stringConverting an array to a string in JavaScript: join with a separator and JSON.stringify.
- How to convert an array to an objectTurning an array into an object in JavaScript: Object.fromEntries, an index by id and pairs of keys and values.
- How to count occurrences of values in an arrayCounting how many times each value occurs in a JavaScript array: an object, Map and filter for one value.
- How to create an array of numbers from 1 to NCreating a range of numbers in JavaScript: Array.from, a step, and an array filled with one value.
- How to filter an arrayFiltering an array in JavaScript with filter: by a condition, removing empty values, objects.
- How to find an element in an array by a conditionSearching an array in JavaScript: find, findIndex, findLast and filter for all matches.
- How to find common elements of two arraysThe intersection of arrays in JavaScript: filter with includes, a Set for speed and Set methods.
- How to find duplicates in an arrayFinding repeated values in a JavaScript array: filter with indexOf, a Set and duplicates by an object field.
- How to find the difference between two arraysElements that are in one array but not in the other in JavaScript: filter, symmetric difference and Set methods.
- How to find the maximum and minimum in an arrayThe largest and smallest value of an array in JavaScript with Math.max, Math.min and reduce.
- How to flatten a nested arrayTurning nested arrays into one in JavaScript: flat with depth, Infinity and flatMap.
- How to get a random element from an arrayA random array element in JavaScript: Math.random with Math.floor, several random elements without repeats.
- How to get the last element of an arrayThe last element of an array in JavaScript: the at method, an index via length and the last few elements.
- How to group an array by a fieldGrouping array elements in JavaScript: Object.groupBy, reduce and counting items in each group.
- How to insert an element into an array at a positionAdding an element to the middle or the beginning of a JavaScript array: splice, toSpliced and unshift.
- How to loop through an array with an indexLooping through an array in JavaScript with access to the index: forEach and entries.
- How to merge two arraysMerging arrays in JavaScript with the spread operator, concat and without duplicates.
- How to remove an element from an arrayRemoving an array element in JavaScript: by value, by index, the first and the last.
- How to remove duplicate objects by a fieldUnique objects in a JavaScript array by id or another field: Map, filter with a Set and keeping the last one.
- How to remove duplicates from an arrayRemoving repeated values from an array in JavaScript with Set, and for an array of objects.
- How to remove empty values from an arrayCleaning an array in JavaScript: filter with Boolean, keeping zeros and removing empty strings.
- How to shuffle an arrayShuffling an array in JavaScript with the Fisher-Yates algorithm and why sort with random is a bad idea.
- How to sort an arraySorting an array in JavaScript: numbers, strings, descending order and by an object field.
- How to sort an array of objects by several fieldsSorting objects in JavaScript by several fields: a comparison function with fallback, strings and descending order.
- How to split an array into chunksDividing an array into parts of a given size in JavaScript: a loop with slice and Array.from.
- How to split an array into pagesPagination of an array in JavaScript: slice by page number and the total number of pages.
- How to sum the values of an arraySum and average of an array in JavaScript with reduce, and summing an object field.
Numbers
- How to calculate a percentagePercentages in JavaScript: the share of a number, a percentage of a number, change in percent and formatting.
- How to check if a number is evenChecking parity and divisibility of a number in JavaScript with the remainder operator.
- How to check if a value is NaNChecking NaN in JavaScript: Number.isNaN, why NaN is not equal to itself and Number.isFinite.
- How to convert a string to a numberConverting a string to a number in JavaScript: Number, parseInt, parseFloat and checking for NaN.
- How to convert bytes to KB, MB and GBShowing a file size in JavaScript in a readable form: a loop over units and Intl.NumberFormat.
- How to format a number with thousands separatorsFormatting numbers in JavaScript with toLocaleString: thousands separators, decimal places and currency.
- How to format a priceFormatting money in JavaScript: Intl.NumberFormat with currency, different countries and cents.
- How to generate a random numberA random number in a range, a random array element and shuffling an array in JavaScript.
- How to limit a number to a rangeClamping a number between a minimum and a maximum in JavaScript with Math.min and Math.max.
- How to round a number to two decimal placesRounding a number to two decimal places in JavaScript: toFixed and Math.round.
- How to round a number up or downRounding in JavaScript: Math.ceil, Math.floor, Math.round, Math.trunc and rounding to tens.
- How to work with very large integersLarge integers in JavaScript: the limit of Number, BigInt and converting BigInt to a string.
- Why 0.1 + 0.2 is not 0.3 and what to do about itFloating point errors in JavaScript: rounding the result, comparing with Number.EPSILON and counting in cents.
Objects
- How to check if an object has a propertyChecking for an object property in JavaScript: Object.hasOwn, the in operator and comparing with undefined.
- How to check if an object is emptyChecking an empty object in JavaScript: Object.keys with length, null and why an empty object is truthy.
- How to compare two objectsComparing objects in JavaScript: by reference, by contents with Object.keys, and nested objects.
- How to convert an object to an arrayGetting arrays from an object in JavaScript: Object.keys, Object.values, Object.entries and an array of objects.
- How to copy an objectCopying an object in JavaScript: a shallow copy with spread and a deep copy with structuredClone.
- How to loop through an object's propertiesLooping through an object's properties in JavaScript: Object.entries, Object.keys and Object.values.
- How to make an object unchangeableProtecting an object from changes in JavaScript: Object.freeze, a shallow freeze and const.
- How to merge objectsCombining objects in JavaScript: the spread operator, Object.assign, which value wins and nested objects.
- How to pick only some fields from an objectTaking the needed properties of an object in JavaScript: destructuring, a pick function and filtering by values.
- How to remove a property from an objectDeleting a key from an object in JavaScript: the delete operator, rest destructuring and removing several keys.
- How to safely read a nested propertyReading deep properties in JavaScript without errors: optional chaining, a default value and calling a method that may be missing.
- How to set a default valueDefault values in JavaScript: the ?? operator, the difference from ||, default parameters and destructuring.
- How to transform all values of an objectChanging every value of an object in JavaScript: Object.entries, map and Object.fromEntries, also for keys.
Date and time
- How to add days, months or hours to a dateDate arithmetic in JavaScript: setDate, setMonth, adding hours and keeping the original date.
- How to calculate age from a date of birthCalculating age in years in JavaScript: the difference of years and the correction for a birthday that has not come yet.
- How to compare two datesComparing dates in JavaScript: the less and greater operators, equality through getTime and comparing only the day.
- How to convert a Unix timestamp to a dateTimestamps in JavaScript: seconds and milliseconds, a date from a timestamp and back.
- How to find the difference between two datesThe difference between dates in JavaScript: the number of days and adding days to a date.
- How to format a dateFormatting a date in JavaScript: toLocaleDateString and building the format by hand.
- How to format a duration in hours, minutes and secondsTurning seconds into 1:05:09 or 2 h 15 min in JavaScript: division with remainder and padStart.
- How to get the current date and timeThe current date and time in JavaScript: new Date, Date.now, separate parts and a formatted string.
- How to get the day of the weekThe day of the week in JavaScript: getDay, the name of the day with toLocaleDateString and Monday as the first day.
- How to get the first and last day of a monthThe beginning and end of a month in JavaScript: day 1, day 0 of the next month and the number of days in a month.
- How to parse a date from a stringTurning a string into a date in JavaScript: ISO format, local dates, the day.month.year format and checking the result.
- How to show a date in another time zoneTime zones in JavaScript: toLocaleString with timeZone, Intl.DateTimeFormat and the time in several cities.
- How to show time agoRelative time in JavaScript: 5 minutes ago and in 2 days with Intl.RelativeTimeFormat.
JSON and web
- How to cancel a fetch requestCancelling a request in JavaScript with AbortController: a cancel button and cancelling an old search request.
- How to convert an object to JSONJSON.stringify in JavaScript: a readable format with indents, choosing fields and what gets lost.
- How to download a file generated in the browserSaving text, JSON or CSV as a file in JavaScript: Blob, URL.createObjectURL and a link with download.
- How to encode and decode Base64Base64 in JavaScript: btoa and atob, text with any letters through TextEncoder, and Base64 for URLs.
- How to encode text for a URLSpecial characters in addresses in JavaScript: encodeURIComponent, decodeURIComponent and the difference from encodeURI.
- How to get the domain from an email or a URLExtracting the domain in JavaScript: the URL object for addresses, split for email and removing www.
- How to handle fetch errorsError handling for requests in JavaScript: network errors, HTTP statuses, invalid JSON and a single helper function.
- How to make an HTTP requestSending GET and POST requests in JavaScript with fetch: reading JSON, sending JSON and headers.
- How to parse a JSON stringTurning JSON into an object in JavaScript: JSON.parse, handling broken JSON and converting dates with a reviver.
- How to parse a URL into partsGetting the protocol, host, path and parameters from an address in JavaScript with the URL object.
- How to parse and build a query stringWorking with the part of an address after the question mark in JavaScript: URLSearchParams, adding parameters and turning them into an object.
- How to set a timeout for fetchLimiting the waiting time of a request in JavaScript: AbortSignal.timeout, AbortController and handling a timeout error.
- How to upload a file with fetchSending files to the server in JavaScript: FormData, several files, extra fields and checking size and type.
Async code
- How to add a timeout to a promiseLimiting the waiting time for a promise in JavaScript: Promise.race with a timer and cleaning up the timer.
- How to debounce a functionDebounce in JavaScript: calling a function only after the user stops typing, with setTimeout and clearTimeout.
- How to handle errors in async codeErrors in promises and async functions in JavaScript: try...catch with await, catch on a promise and unhandled rejections.
- How to retry a failed operationRepeating a request on error in JavaScript: a loop with attempts, a growing pause and which errors to retry.
- How to run async operations one after anotherSequential execution in JavaScript: await in a for...of loop, passing the result on and why forEach does not work.
- How to run async tasks in parallel with a limitLimiting concurrency in JavaScript: a pool of workers so that no more than N requests run at the same time.
- How to run code repeatedly at an intervalRepeating actions in JavaScript: setInterval, stopping with clearInterval and a chain of setTimeout calls.
- How to run several async operations in parallelParallel requests in JavaScript: Promise.all, the results in order and Promise.allSettled when some fail.
- How to throttle a functionThrottle in JavaScript: calling a function no more often than once per interval, for scroll and resize.
- How to turn a callback function into a promiseWrapping old callback-style APIs in JavaScript: new Promise, resolve and reject, and util.promisify in Node.js.
- How to wait before running codeA pause in JavaScript: setTimeout, a sleep function with a promise and await, and pauses in a loop.
DOM and browser
- How to add a dark mode toggleA light and dark theme in JavaScript: a class on html, CSS variables, the system setting and remembering the choice.
- How to add, remove or toggle a CSS classWorking with classes in JavaScript: classList.add, remove, toggle, contains and replace.
- How to copy text to the clipboardCopying to the clipboard in JavaScript: navigator.clipboard.writeText, a copy button and handling errors.
- How to create an element and add it to the pageCreating HTML elements in JavaScript: createElement, append, prepend, a list from an array and a template.
- How to detect a click outside an elementClosing a menu or a popup on a click outside in JavaScript: contains, closest and the Escape key.
- How to detect when an element becomes visibleIntersectionObserver in JavaScript: an animation on appearance, lazy loading and infinite scroll.
- How to get data from a formReading form fields in JavaScript: FormData, turning it into an object, checkboxes and several values.
- How to get query parameters from the page addressReading parameters from the current URL in JavaScript: location.search, URLSearchParams and changing parameters without reloading.
- How to react to the Enter key and other keysKeyboard events in JavaScript: keydown, event.key, keyboard shortcuts and Enter in a text field.
- How to redirect to another pageNavigation in JavaScript: location.href, location.replace, opening a new tab and reloading the page.
- How to save an object to localStorageStoring data in the browser with JavaScript: JSON.stringify for saving, JSON.parse for reading and a default value.
- How to scroll to an elementScrolling a page in JavaScript: scrollIntoView with smooth scrolling, scrolling to the top and an offset for a fixed header.
- How to set and read a cookieCookies in JavaScript: document.cookie, the lifetime of a cookie, reading by name and deleting.
Validation
- How to check if a date is validValidating dates in JavaScript: an invalid Date, February 30 and checking a date string in the YYYY-MM-DD format.
- How to check if a string is a numberValidating numeric input in JavaScript: Number with isFinite, integers only, ranges and why parseFloat is too lenient.
- How to check if a string is a valid URLValidating a URL in JavaScript: URL.canParse, new URL with try...catch and allowing only http and https.
- How to check password strengthPassword rules in JavaScript: length, letters, digits and symbols, a list of unmet requirements and a strength score.
- How to validate a form before submittingForm validation in JavaScript: HTML attributes, checkValidity, custom messages with setCustomValidity and showing errors.
- How to validate a phone numberChecking phone numbers in JavaScript: removing formatting, checking the number of digits and the international format.
- How to validate an email addressChecking an email in JavaScript: a simple regular expression, the email field in HTML and why a perfect check is impossible.
Node.js
- How to append to a file in Node.jsAdding lines to the end of a file in Node.js: appendFile, a simple log with dates and a write stream.
- How to calculate a hash of a stringSHA-256 and MD5 in JavaScript: createHash in Node.js and crypto.subtle.digest in the browser.
- How to check if a file exists in Node.jsChecking a file in Node.js: existsSync, access with promises, stat for files and folders, and why it is often better to just open the file.
- How to create a folder in Node.jsCreating directories in Node.js: mkdir, nested folders with recursive, a temporary folder and removing a folder.
- How to delete a file in Node.jsRemoving files in Node.js: unlink, rm with force for a file that may be missing, and deleting files by a pattern.
- How to get a file extensionThe extension and the name of a file in JavaScript: path.extname and basename in Node.js, and lastIndexOf in the browser.
- How to list the files in a folder in Node.jsReading a directory in Node.js: readdir, files and folders separately, filtering by extension and all files recursively.
- How to read a CSV file in JavaScriptParsing CSV in JavaScript and Node.js: lines and columns, objects from the header row and values in quotes.
- How to read a file in Node.jsReading a text file in Node.js: readFile from node:fs/promises, the encoding, a missing file and readFileSync.
- How to read a file line by line in Node.jsProcessing a large file in Node.js: readline with a stream, for await, and split for small files.
- How to read an environment variable in Node.jsEnvironment variables in Node.js: process.env, default values, numbers and flags, and a .env file.
- How to read and write a JSON file in Node.jsA JSON file in Node.js: readFile with JSON.parse, writing with JSON.stringify and a readable format, a damaged file.
- How to read command-line arguments in Node.jsArguments of a Node.js script: process.argv, skipping the first two elements and parsing options with util.parseArgs.
- How to write to a file in Node.jsWriting text to a file in Node.js: writeFile, creating and overwriting, writing an array of lines and creating folders.
Miscellaneous
- How to check the type of a variableTypes in JavaScript: typeof, the special cases of null and arrays, instanceof and a universal type function.
- How to generate a random passwordA secure random password in JavaScript: crypto.getRandomValues, required character groups and shuffling.
- How to generate a UUIDA unique identifier in JavaScript: crypto.randomUUID in the browser and Node.js, and checking the UUID format.
- How to inspect a variable while debuggingDebugging output in JavaScript: console.log with labels, JSON.stringify, console.table and the debugger statement.
- How to measure how long code takesMeasuring execution time in JavaScript: performance.now, console.time and timing async operations.