JavaScript reference
JavaScript reference
JavaScript functions, classes and methods: syntax, parameters, return values and examples.
Strings
- String.prototype.atReturns the character at a position; negative indexes are allowed.
- String.prototype.charAtReturns the character at a position.
- String.prototype.charCodeAtReturns the numeric code of a character.
- String.prototype.concatJoins strings together.
- String.prototype.endsWithChecks whether a string ends with the given text.
- String.fromCharCodeCreates a string from character codes.
- String.prototype.includesChecks whether a string contains a given substring.
- String.prototype.indexOfFinds the position of the first occurrence of a substring.
- String.prototype.lastIndexOfFinds the last occurrence of a text in a string.
- String.prototype.lengthThe length of a string — how many characters it has.
- String.prototype.localeCompareCompares strings by language rules — for alphabetical sorting.
- String.prototype.padEndPads a string on the right to the desired length.
- String.prototype.padStartPads a string on the left to a given length.
- String.rawA template literal without escape-sequence processing.
- String.prototype.repeatRepeats a string a given number of times.
- String.prototype.replaceReplaces the first match (or all of them with a regex g flag).
- String.prototype.replaceAllReplaces all occurrences of a substring with another string.
- String.prototype.sliceReturns part of a string.
- String.prototype.splitSplits a string into an array by a separator.
- String.prototype.startsWithChecks whether a string starts with a given substring.
- String.prototype.substringReturns the part of a string between two positions.
- String.prototype.toLowerCaseConverts a string to lowercase.
- String.prototype.toUpperCaseConverts a string to uppercase.
- String.prototype.trimRemoves whitespace from both ends of a string.
- String.prototype.trimEndRemoves whitespace and line breaks from the end of a string.
- String.prototype.trimStartRemoves whitespace and line breaks from the start of a string.
- Template literalA string in backticks with substitutions and line breaks.
Arrays
- Array.prototype.atReturns the element at an index; negative indexes are allowed.
- Array.prototype.concatMerges arrays into a new array.
- Array.prototype.entriesReturns index–element pairs for a for...of loop.
- Array.prototype.everyChecks that every element of an array passes a test.
- Array.prototype.fillFills an array with one value.
- Array.prototype.filterCreates a new array from the elements that pass a test.
- Array.prototype.findReturns the first element that passes a test.
- Array.prototype.findIndexReturns the index of the first element that passes a test.
- Array.prototype.findLastSearches from the end of an array for the first element that passes a test.
- Array.prototype.findLastIndexReturns the index of the last element that passes a test.
- Array.prototype.flatFlattens nested arrays into one.
- Array.prototype.flatMapMaps each element with a function and flattens the result one level.
- Array.prototype.forEachRuns a function for every element of an array.
- Array.fromCreates an array from a string, Set, Map or another iterable.
- Array.prototype.includesChecks whether an array contains a value.
- Array.prototype.indexOfFinds a value in an array and returns its index.
- Array.isArrayChecks whether a value is an array.
- Array.prototype.joinJoins array elements into a string.
- Array.prototype.keysReturns the indexes of an array.
- Array.prototype.lastIndexOfFinds a value from the end of an array and returns its index.
- Array.prototype.lengthThe number of elements in an array.
- Array.prototype.mapCreates a new array by transforming every element.
- Array.ofCreates an array from its arguments.
- Array.prototype.popRemoves the last element of an array and returns it.
- Array.prototype.pushAppends elements to the end of an array.
- Array.prototype.reduceReduces an array to a single value.
- Array.prototype.reduceRightReduces an array to one value, going from right to left.
- Array.prototype.reverseReverses an array in place.
- Array.prototype.shiftRemoves the first element of an array and returns it.
- Array.prototype.sliceReturns part of an array.
- Array.prototype.someChecks whether at least one element passes a test.
- Array.prototype.sortSorts the elements of an array.
- Array.prototype.spliceRemoves, replaces or inserts elements in the middle of an array.
- Array.prototype.toReversedReturns a reversed copy of an array.
- Array.prototype.toSortedReturns a sorted copy of an array without changing the original.
- Array.prototype.toSplicedReturns a copy of an array with elements removed, replaced or inserted.
- Array.prototype.unshiftAdds elements to the beginning of an array.
- Array.prototype.withReturns a copy of an array with one element replaced.
Numbers and Math
- BigIntIntegers of any size, without loss of precision.
- isFiniteChecks that a value converts to a finite number.
- isNaNChecks whether converting a value to a number gives NaN.
- Math.absReturns the absolute value of a number — its value without the sign.
- Math.ceilRounds a number up to an integer.
- Math.floorRounds a number down to an integer.
- Math.maxReturns the largest of the given numbers.
- Math.minReturns the smallest of the given numbers.
- Math.PIThe constant π — the ratio of a circle's circumference to its diameter.
- Math.powRaises a number to a power.
- Math.randomReturns a random number between 0 and 1.
- Math.roundRounds a number to the nearest integer.
- Math.signReturns the sign of a number: 1, -1 or 0.
- Math.sqrtReturns the square root of a number.
- Math.truncDrops the fractional part of a number.
- NaNThe special Not-a-Number value — the result of a failed math operation.
- Number()Converts a value to a number.
- Number.EPSILONThe smallest difference between 1 and the next number — for comparing fractions.
- Number.isFiniteChecks that a value is a finite number (not NaN and not Infinity).
- Number.isIntegerChecks whether a value is an integer.
- Number.isNaNChecks that a value is NaN, without type conversion.
- Number.isSafeIntegerChecks that an integer is within the range where it is stored exactly.
- Number.MAX_SAFE_INTEGERThe largest integer that is stored without losing precision.
- Number.prototype.toFixedFormats a number with a given number of decimal places.
- Number.prototype.toLocaleStringFormats a number by language rules: digit grouping, currency, percent.
- Number.prototype.toPrecisionFormats a number with a given number of significant digits.
- Number.prototype.toStringConverts a number to a string, including in another numeral system.
- parseFloatReads a floating-point number from the start of a string.
- parseIntConverts a string to an integer.
Objects and JSON
- JSON.parseParses a JSON string and returns the value.
- JSON.stringifyConverts a value to a JSON string.
- Object.assignCopies properties from some objects into another.
- Object.createCreates an object with the given prototype.
- Object.definePropertyDefines a property with exact settings: read-only, hidden, with a getter.
- Object.entriesReturns an array of property name and value pairs.
- Object.freezePrevents any changes to an object.
- Object.fromEntriesCreates an object from a list of key–value pairs.
- Object.getPrototypeOfReturns the prototype of an object.
- Object.groupByGroups the elements of an array by a key.
- Object.hasOwnChecks whether an object has its own property.
- Object.prototype.hasOwnPropertyChecks whether an object has its own property (the older way).
- Object.isCompares two values almost like === but handles NaN and -0 correctly.
- Object.isFrozenChecks whether an object is frozen.
- Object.keysReturns an array of an object's property names.
- Object.sealForbids adding and removing properties but lets existing ones change.
- Object.valuesReturns an array of an object's property values.
Map and Set
- MapA collection of key–value pairs where a key can be anything.
- Map.prototype.clearRemoves all entries from a Map.
- Map.prototype.deleteRemoves the entry for a key.
- Map.prototype.entriesReturns the key–value pairs of a Map.
- Map.prototype.forEachCalls a function for each entry of a Map.
- Map.prototype.getReturns the value for a key.
- Map.groupByGroups elements into a Map by any key.
- Map.prototype.hasChecks whether a key is in a Map.
- Map.prototype.keysReturns the keys of a Map.
- Map.prototype.setAdds or replaces the value for a key.
- Map.prototype.sizeThe number of entries in a Map.
- Map.prototype.valuesReturns the values of a Map.
- SetA collection of unique values.
- Set.prototype.addAdds a value to a Set if it is not there yet.
- Set.prototype.clearRemoves all values from a Set.
- Set.prototype.deleteRemoves a value from a Set.
- Set.prototype.differenceReturns the values that are only in the first set.
- Set.prototype.forEachCalls a function for each value of a Set.
- Set.prototype.hasChecks whether a value is in a Set.
- Set.prototype.intersectionReturns the values two sets have in common.
- Set.prototype.isSubsetOfChecks that every value of a set is in another one.
- Set.prototype.sizeThe number of values in a Set.
- Set.prototype.unionCombines two sets.
- WeakMapA Map whose keys must be objects and do not prevent garbage collection.
- WeakSetA set of objects that does not prevent their garbage collection.
Date and time
- DateA date and time: creating, reading parts, calculating.
- Date.prototype.getDateReturns the day of the month.
- Date.prototype.getDayReturns the day of the week — a number from 0 to 6, where 0 is Sunday.
- Date.prototype.getFullYearReturns the year.
- Date.prototype.getHoursReturns the hour.
- Date.prototype.getMinutesReturns the minutes.
- Date.prototype.getMonthReturns the month — a number from 0 to 11.
- Date.prototype.getSecondsReturns the seconds.
- Date.prototype.getTimeReturns the date as a number of milliseconds.
- Date.prototype.getTimezoneOffsetReturns the time zone offset in minutes.
- Date.nowReturns the current time as a number of milliseconds.
- Date.parseParses a date string and returns a timestamp.
- Date.prototype.setDateSets the day of the month — handy for adding and subtracting days.
- Date.prototype.setFullYearSets the year, and optionally the month and day.
- Date.prototype.setHoursSets the hour, and optionally minutes, seconds and milliseconds.
- Date.prototype.setMonthSets the month.
- Date.prototype.toISOStringReturns the date in ISO 8601 format in UTC.
- Date.prototype.toLocaleDateStringFormats a date without time by language rules.
- Date.prototype.toLocaleStringFormats a date together with the time by language rules.
- Date.prototype.toLocaleTimeStringFormats a time without the date by language rules.
- Date.UTCReturns the timestamp of a date given in UTC.
Formatting (Intl)
- Intl.CollatorCompares strings by language rules — for fast alphabetical sorting.
- Intl.DateTimeFormatFormats dates and times by language rules.
- Intl.ListFormatJoins a list into a phrase with commas and a conjunction: a, b, and c.
- Intl.NumberFormatFormats numbers, currencies, percents and units by language rules.
- Intl.PluralRulesPicks the word form for a number: 1 file, 2 files.
- Intl.RelativeTimeFormatFormats relative time: 3 days ago, in 1 hour.
Regular expressions
- RegExpA regular expression — a pattern for finding and replacing text.
- RegExp.escapeEscapes a string so it can be safely put into a regular expression.
- RegExp.prototype.execFinds a match and returns the details: groups and position.
- RegExp flagsFlags change how matching works: g for all matches, i for case-insensitive, and more.
- Named capture groupsNamed groups — parts of a match with readable names.
- RegExp.prototype.testChecks whether a string matches a pattern.
- String.prototype.matchFinds matches of a regular expression.
- String.prototype.matchAllReturns every match together with its groups.
- String.prototype.searchReturns the position of the first regex match.
Operators
- deleteRemoves a property from an object.
- Destructuring assignmentUnpacks values from an array or object into separate variables.
- Exponentiation (**)Raises a number to a power.
- inChecks whether an object has a property (inherited ones included).
- Increment and decrement (++ --)Increases or decreases a variable by one.
- instanceofChecks whether an object was created by a class (or a subclass).
- Logical AND (&&)Logical AND: returns the first falsy value, or the last one.
- Logical assignment (??=, ||=, &&=)Assigns a value only if the variable is nullish, falsy or truthy.
- Logical OR (||)Logical OR: returns the first truthy value.
- newCreates a new object using a class or a constructor function.
- Nullish coalescing (??)Returns the right-hand value if the left is null or undefined.
- Optional chaining (?.)Safe property access: returns undefined instead of an error if the object is missing.
- Remainder (%)The remainder of a division.
- Spread syntaxThree dots spread an array or object into separate items.
- Strict equality (===)Compares values without type conversion.
- Conditional (ternary) operatorPicks one of two values by a condition — a short if...else.
- typeofReturns a string with the type of a value.
Variables and statements
- constDeclares a variable that cannot be reassigned.
- for...inLoops over the property names of an object.
- for...ofLoops over the values of arrays, strings, Maps, Sets and other iterables.
- letDeclares a variable whose value can change.
- switchPicks a branch of code by value.
- 'use strict'Enables strict mode: errors that used to be silent become explicit.
- varThe legacy way to declare a variable.
Functions
- Arrow function (=>)A short way to write a function.
- Default parametersA parameter's value when no argument is passed.
- Function.prototype.applyCalls a function with a given this and an array of arguments.
- Function.prototype.bindCreates a copy of a function with a fixed this and, optionally, arguments.
- Function.prototype.callCalls a function with a given this and arguments.
- Rest parametersCollects the remaining function arguments into an array.
Classes
- classDeclares a class — a template for objects with shared methods.
- extendsCreates a subclass that inherits the parent's properties and methods.
- get / setProperties backed by functions: reading calls get, writing calls set.
- Private fields (#)Fields and methods accessible only inside the class.
- staticA method or property of the class itself, not of its objects.
- superCalls the parent class's constructor or method.
Errors
- AggregateErrorSeveral errors in one — thrown by Promise.any.
- ErrorThe base error class: created and thrown with throw.
- Error.prototype.causeThe original reason for an error — so it is not lost when rethrowing.
- RangeErrorAn out-of-range value error.
- ReferenceErrorA variable does not exist error.
- SyntaxErrorA syntax error — in code, in JSON or in a regular expression.
- throwThrows an error and stops the function.
- try...catchCatches errors so the program does not stop.
- TypeErrorA wrong type error — for example, calling a method on undefined.
Promises and async
- async functionA function that always returns a promise and lets you use await inside.
- awaitWaits for a promise and returns its value.
- fetchSends an HTTP request and returns a promise of the response.
- for await...ofLoops over asynchronous data sources, waiting for each item.
- PromiseA promise of a result that will be ready later: success or failure.
- Promise.allWaits for all promises in parallel.
- Promise.allSettledWaits for every promise to settle and reports each result — success or failure.
- Promise.anyReturns the first successful result and skips errors.
- Promise.prototype.catchHandles a promise's error.
- Promise.prototype.finallyRuns an action after a promise — on success and on failure.
- Promise.raceReturns the result of the first promise to settle — successful or not.
- Promise.rejectCreates a promise that is already rejected with an error.
- Promise.resolveCreates a promise that is already fulfilled with a value.
- Promise.prototype.thenSays what to do with a promise's result.
- Promise.withResolversCreates a promise and hands out its resolve and reject functions.
Global functions
- atobDecodes a Base64 string.
- Boolean()Converts a value to true or false.
- btoaEncodes a string to Base64.
- clearIntervalStops a repeating setInterval.
- clearTimeoutCancels a scheduled setTimeout.
- crypto.randomUUIDCreates a random unique identifier (UUID).
- decodeURIComponentDecodes text that was encoded for a URL.
- encodeURIComponentEncodes text for safely putting it into part of a URL.
- globalThisThe global object, available the same way in browsers, workers and Node.js.
- queueMicrotaskQueues a function as a microtask — it runs before any timer.
- setIntervalRuns a function again and again at an interval.
- setTimeoutRuns a function once after a delay.
- String()Converts any value to a string.
- structuredCloneCreates a deep copy of an object with all nested data.
- URLParses an address into parts and builds it back.
- URLSearchParamsReads and builds URL query parameters (the part after ?).
Symbols and iterators
- function*A generator function: produces values one at a time with yield.
- SymbolCreates a unique value — for example, a key that never clashes with others.
- Symbol.forReturns a shared symbol by name: the same name gives the same symbol.
- Symbol.iteratorA special key that makes an object iterable in for...of and spread.
Console
- console.assertPrints an error to the console only if a condition is false.
- console.countCounts how many times this line was called.
- console.dirShows an object as a tree of properties.
- console.errorPrints an error message — highlighted in red in the console.
- console.groupGroups console messages into a collapsible, indented block.
- console.infoPrints an informational message.
- console.logPrints values to the console.
- console.tableShows an array of objects as a table in the browser console.
- console.timeMeasures how long code took to run.
- console.tracePrints the chain of calls that led to this line.
- console.warnPrints a warning — highlighted in yellow in the console.