omprehensive JavaScript Methods
C
Guide
avaScript has a vast array of built-in methods that operate on different data types
J
and objects. Here's a breakdown of common categories and some key methods within
them, along with their primary use cases:
1. Array Methods
hese methods are designed to work with arrays, which are ordered lists of data. They
T
are extremely common in web development.
● push():
○ What it does:Adds one or more elements to theendof an array.
○ When to use:When you need to append new items to an existing list, like
dding a new item to a shopping cart or a new message to a chat feed.
a
● pop():
○ What it does:Removes thelastelement from an array and returns that
element.
○ When to use:When you need to process items in a "last-in, first-out" (LIFO)
manner, like implementing an "undo" feature or managing a stack.
● shift():
○ What it does:Removes thefirstelement from an array and returns that
element.
○ When to use:When you need to process items in a "first-in, first-out" (FIFO)
manner, like a queue of tasks.
● unshift():
○ What it does:Adds one or more elements to thebeginningof an array.
○ When to use:When you need to prepend new items to a list, perhaps for
prioritizing certain elements.
● concat():
○ What it does:Merges two or more arrays to create anewarray. It doesn't
modify the original arrays.
○ When to use:When you want to combine lists of data without altering the
original sources.
● slice():
○ What it does:Extracts a portion of an array into anewarray, without
modifying the original.
○ When to use:When you need a subset of an array, like for pagination
( showing only a few items at a time) or creating a shallow copy of part of an
array.
● splice():
○ What it does:Changes the contents of an array by removing or replacing
existing elements and/or adding new elementsin place.
○ When to use:For more complex array modifications where you need to add,
remove, or replace elements at specific positions directly within the original
array.
● forEach():
○ What it does:Executes a provided function once for each array element.
○ When to use:When you need to perform an action for every item in an array,
such as logging each item or updating a display for each item. It doesn't
return a new array.
● map():
○ What it does:Creates anewarray by calling a provided function on every
element in the calling array.
○ When to use:When you want to transform each element in an array into a
new value, e.g., converting a list of numbers to their squares, or a list of
objects to just their names.
● filter():
○ What it does:Creates anewarray with all elements that pass a test
implemented by the provided function.
○ When to use:When you need to select a subset of elements from an array
based on a specific condition, e.g., finding all even numbers, or users older
than 18.
● reduce():
○ What it does:Executes a "reducer" callback function on each element of the
array, resulting in asingle output value.
○ When to use:When you need to combine all elements of an array into a single
value, such as calculating a sum, average, or flattening a nested array.
● find():
○ What it does:Returns thefirstelement in the array that satisfies the provided
testing function.
○ When to use:When you need to find a specific item in an array that meets a
certain condition, and you only care about the first match.
● findIndex():
○ What it does:Returns theindexof the first element in the array that satisfies
the provided testing function.
○ When to use:When you need to find the position of a specific item in an
rray that meets a certain condition.
a
● includes():
○ What it does:Determines whether an array includes a certain value, returning
true or false.
○ When to use:When you just need to check for the presence of an element in
an array.
● sort():
○ What it does:Sorts the elements of an arrayin placeand returns the sorted
array. By default, it sorts alphabetically (as strings).
○ When to use:To arrange elements in a specific order (ascending,
descending, custom). Requires a compare function for numerical or complex
object sorting.
● reverse():
○ What it does:Reverses the order of the elements in an arrayin place.
○ When to use:To quickly flip the order of elements in an array.
● at() (Added):
○ What it does:Returns the element at a specified index, allowing for negative
indices to count from the end of the array.
○ When to use:When you need to access elements from the end of an array
without knowing its exact length (e.g., [Link](-1) for the last element).
● flat() (Added):
○ What it does:Creates a new array with all sub-array elements concatenated
into it recursively up to the specified depth.
○ When to use:To flatten nested arrays into a single-level array.
● flatMap() (Added):
○ What it does:Maps each element using a mapping function, then flattens the
result into a new array. It's equivalent to map() followed by flat() with depth 1.
○ When to use:When you want to map and flatten an array in a single
operation, especially when your mapping function returns arrays.
● [Link]() (Static Method - Added):
○ What it does:Creates a new, shallow-copied Array instance from an
array-like or iterable object.
○ When to use:To convert NodeLists (from DOM queries), Sets, or Strings into
true arrays, or to create arrays with a specified length and initial values.
● [Link]() (Static Method - Added):
○ What it does:Determines whether the passed value is an Array.
○ When to use:To reliably check if a variable holds an array, as typeof []
returns "object".
2. String Methods
These methods operate on strings, which are sequences of characters.
● length (property, not a method, but commonly used):
○ What it does:Returns the length of the string (number of characters).
○ When to use:To get the number of characters in a string.
● indexOf():
○ What it does:Returns the index of the first occurrence of a specified value
ithin a string. Returns -1 if not found.
w
○ When to use:To find if a substring exists within a string and where it starts.
● includes():
○ What it does:Determines whether a string contains the characters of a
specified string, returning true or false.
○ When to use:To simply check for the presence of a substring.
● slice():
○ What it does:Extracts a section of a string and returns a new string.
○ When to use:To get a part of a string, similar to array slice.
● substring():
○ What it does:Similar to slice(), but handles negative arguments differently
(treats them as 0).
○ When to use:To extract a part of a string, particularly when you need
specific behavior for negative start/end indices.
● toUpperCase():
○ What it does:Converts a string to uppercase letters.
○ When to use:For case-insensitive comparisons, standardizing input, or
formatting text.
● toLowerCase():
○ What it does:Converts a string to lowercase letters.
○ When to use:For case-insensitive comparisons, standardizing input, or
formatting text.
● trim():
○ What it does:Removes whitespace from both ends of a string.
○ When to use:To clean up user input or data that might have unintended
leading or trailing spaces.
● split():
○ What it does:Divides a string into an ordered list of substrings, puts these
substrings into an array, and returns the array.
○ When to use:To break a string into smaller parts based on a delimiter (e.g.,
s plitting a sentence into words, or a CSV string into an array of values).
● join() (Array Method - Related):
○ What it does:Joins all elements of an array into a string.
○ When to use:To reconstruct a string from an array of strings, often after
using split().
● replace():
○ What it does:Searches a string for a value or a regular expression, and
returns a new string with the specified values replaced. Only replaces the first
match by default.
○ When to use:To substitute parts of a string, like fixing typos or sanitizing
input. Use replaceAll() or a regex with the g flag for all occurrences.
● startsWith() (Added):
○ What it does:Determines whether a string begins with the characters of a
specified string, returning true or false.
○ When to use:To check if a string starts with a particular prefix.
● endsWith() (Added):
○ What it does:Determines whether a string ends with the characters of a
specified string, returning true or false.
○ When to use:To check if a string ends with a particular suffix.
● repeat() (Added):
○ What it does:Constructs and returns a new string which contains the
specified number of copies of the string on which it was called, concatenated
together.
○ When to use:For simple string repetition, like creating separators or patterns.
3. Object Methods
These methods interact with JavaScript objects (key-value pairs).
● [Link]():
○ What it does:Returns an array of a given object's own enumerable property
ames.
n
○ When to use:To get a list of all the property names (keys) of an object.
[Link]():
●
○ What it does:Returns an array of a given object's own enumerable property
values.
○ When to use:To get a list of all the values of an object's properties.
● [Link]():
○ What it does:Returns an array of a given object's own enumerable
s tring-keyed property [key, value] pairs.
○ When to use:To easily iterate over both the keys and values of an object, or
to convert an object into an array of [key, value] pairs.
● [Link]():
○ What it does:Copies all enumerable own properties from one or more source
objects to a target object. It returns the target object.
○ When to use:To merge objects or create shallow copies of objects.
● hasOwnProperty():
○ What it does:Returns a boolean indicating whether the object has the
specified property as its own (not inherited from its prototype chain).
○ When to use:To safely check if an object directly contains a property before
trying to access it, avoiding issues with inherited properties.
● [Link]() (Added):
○ What it does:Freezes an object, preventing new properties from being
added to it, existing properties from being removed, and existing properties
from being changed.
○ When to use:To make an object immutable, ensuring its state cannot be
altered after creation.
● [Link]() (Added):
○ What it does:Seals an object, preventing new properties from being added
and marking all existing properties as non-configurable. Property values can
still be changed.
○ When to use:When you want to restrict the addition/deletion of properties
but allow modification of existing ones.
4. Math Methods
hese methods are part of the built-in Math object and perform mathematical
T
operations.
● [Link]():
○ What it does:Returns the value of a number rounded to the nearest integer.
○ When to use:For standard rounding of decimal numbers.
● [Link]():
○ What it does:Returns the largest integer less than or equal to a given
umber (rounds down).
n
○ When to use:To round a numberdownto the nearest whole number.
[Link]():
●
○ What it does:Returns the smallest integer greater than or equal to a given
number (rounds up).
○ When to use:To round a numberupto the nearest whole number.
● [Link]():
○ What it does:Returns a pseudo-random floating-point number between 0
( inclusive) and 1 (exclusive).
○ When to use:For generating random numbers, like for games, unique IDs, or
shuffling arrays.
● [Link]():
○ What it does:Returns the absolute value of a number.
○ When to use:To get the positive magnitude of a number.
● [Link]():
○ What it does:Returns the largest of zero or morenumbers.
○ When to use:To find the highest value among a setof numbers.
● [Link]():
○ What it does:Returns the smallest of zero or morenumbers.
○ When to use:To find the lowest value among a setof numbers.
● [Link]() (Added):
○ What it does:Returns the integer part of a numberby removing any
fractional digits.
○ When to use:To simply remove the decimal part ofa number without
rounding.
● [Link]() (Added):
○ What it does:Returns the base to the exponent power,that is,
base^exponent.
○ When to use:For calculating powers of numbers.
● [Link]() (Added):
○ What it does:Returns the square root of a number.
○ When to use:For calculating square roots.
5. Date Methods
hese methods are part of the built-in Date object and are used to work with dates
T
and times.
● new Date():
○ What it does:Creates a new Date object representingthe current date and
t ime, or a specified date and time.
○ When to use:To get the current date/time, or to createa date object from a
string, milliseconds, or individual date components.
getFullYear():
●
○ What it does:Returns the year (4 digits) of a date.
○ When to use:To extract the year from a date.
● getMonth():
○ What it does:Returns the month (0-11) of a date.(Note: January is 0,
ecember is 11).
D
○ When to use:To extract the month from a date.
● getDate():
○ What it does:Returns the day of the month (1-31)of a date.
○ When to use:To extract the day of the month.
● getHours(), getMinutes(), getSeconds(), getMilliseconds():
○ What they do:Return the respective time components.
○ When to use:To extract specific time units from adate.
● getTime():
○ What it does:Returns the number of milliseconds sinceJanuary 1, 1970,
00:00:00 UTC (Epoch time).
○ When to use:For comparing dates, or for time calculations,as timestamps
are easy to compare.
● toLocaleString():
○ What it does:Returns a string with a language-sensitiverepresentation of
the date's date portion (and optionally time).
○ When to use:To format dates and times according tolocal conventions (e.g.,
"MM/DD/YYYY" vs "DD/MM/YYYY", or different time formats).
● toISOString() (Added):
○ What it does:Returns the date in the ISO 8601 extendedformat
(YYYY-MM-DDTHH:mm:[Link]).
○ When to use:For standardized date representation,especially when sending
dates to a server or between systems.
● [Link]() (Static Method - Added):
○ What it does:Parses a string representation of adate and returns the
number of milliseconds since January 1, 1970, 00:00:00 UTC.
○ When to use:To convert a date string into a timestamp,which can then be
used to create a Date object.
6. Console Methods (for Debugging)
hese methods are part of the global console object and are essential for debugging
T
and logging information in the browser or [Link] environment.
● [Link]():
○ What it does:Outputs a message to the web console.
○ When to use:For general debugging, displaying variablevalues, or tracking
ode execution.
c
● [Link]():
○ What it does:Outputs a warning message to the console,typically styled
differently (e.g., yellow background).
○ When to use:To indicate potential issues that arenot critical errors but
should be noted by developers.
● [Link]():
○ What it does:Outputs an error message to the console,typically styled
differently (e.g., red background) and includes a stack trace.
○ When to use:To log errors or exceptions that occurin your code, helping in
identifying the source of problems.
● [Link]():
○ What it does:Displays tabular data (like arrays ofobjects or single objects)
as a table in the console.
○ When to use:To inspect arrays of objects or complexdata structures in a
more readable, organized table format.
● [Link]() (Added):
○ What it does:Logs the number of times that count()has been called with the
given label.
○ When to use:To track how many times a specific pieceof code or a function
is executed.
● [Link]() / [Link]() (Added):
○ What they do:Start a timer with a label (time())and stop it, logging the
elapsed time in milliseconds (timeEnd()).
○ When to use:To measure the performance or executiontime of a block of
code.
7. Global Object Methods / Functions (Added)
These are functions available globally in JavaScript, not tied to a specific object type.
● parseInt():
○ What it does:Parses a string argument and returnsan integer of the
s pecified radix (the base in mathematical numeral systems).
○ When to use:To convert a string to a whole number,often from user input
(e.g., "123px" to 123).
parseFloat():
●
○ What it does:Parses a string argument and returnsa floating-point number.
○ When to use:To convert a string to a decimal number.
● isNaN():
○ What it does:Determines whether a value is NaN (Not-a-Number).
○ When to use:To reliably check if a variable's valueis NaN, as NaN === NaN is
f alse.
isFinite():
●
○ What it does:Determines whether a value is a finitenumber.
○ When to use:To check if a number is not Infinity,-Infinity, or NaN.
● encodeURI() / decodeURI():
○ What they do:Encode/decode a URI (Uniform ResourceIdentifier) by
escaping/unescaping certain characters.
○ When to use:For handling full URIs, like when constructingor parsing URLs.
● encodeURIComponent() / decodeURIComponent():
○ What they do:Encode/decode a URI component by escaping/unescaping
characters.
○ When to use:For handling parts of a URI, like queryparameters, to ensure
they are correctly formatted for URLs.
8. JSON Methods (Added)
he JSON object provides methods for working with JSON (JavaScript Object
T
Notation) data.
● [Link]():
○ What it does:Parses a JSON string, constructing theJavaScript value or
bject described by the string.
o
○ When to use:To convert a JSON string (e.g., receivedfrom a server) into a
usable JavaScript object or array.
[Link]():
●
○ What it does:Converts a JavaScript value (objector array) to a JSON string.
○ When to use:To convert a JavaScript object/arrayinto a JSON string,
typically for sending it to a server or storing it in local storage.
9. DOM Manipulation Methods (Web-Specific - Added)
hese methods are crucial for interacting with HTML elements in a web browser. They
T
are part of the Document object and element objects.
● [Link]():
○ What it does:Returns an Element object representingthe element whose id
roperty matches the specified string.
p
○ When to use:To get a reference to a single HTML elementby its unique id.
[Link]():
●
○ What it does:Returns thefirstElement within thedocument that matches the
s pecified CSS selector.
○ When to use:To get a reference to a single HTML elementusing CSS
selectors (more flexible than getElementById).
● [Link]():
○ What it does:Returns a static (non-live) NodeListrepresenting a list of the
document's elements that match the specified group of selectors.
○ When to use:To get references to multiple HTML elementsthat match a CSS
selector.
● [Link]():
○ What it does:Attaches an event handler function toa specified element
when an event occurs.
○ When to use:To make HTML elements interactive, suchas responding to
clicks, key presses, form submissions, etc.
● [Link]():
○ What it does:Creates a new HTML element of the specifiedtag name.
○ When to use:To dynamically create new HTML elementsfrom JavaScript.
● [Link]():
○ What it does:Adds a node to the end of the list ofchildren of a specified
parent node.
○ When to use:To insert a newly created element intothe DOM.
● [Link] (property, not a method):
○ What it does:Represents the text content of a nodeand its descendants.
○ When to use:To get or set the plain text contentof an HTML element.
● [Link] (property, not a method):
○ What it does:Represents the HTML content of an element.
○ When to use:To getor set the HTML structure within an element. Be cautious
as it can be a security risk if used with untrusted input.