You are on page 1of 4

JavaScript Cheat Sheet

>= Greater than or equal to \b Backspace


JavaScript Arrays
<= Lesser than or equal to \f Form feed
concat() Join several arrays into one
? Ternary operator \n New line
Copy array elements within the array,
copyWithin() to and from specified positions \r Carriage return
Logical Operators
Return the primitive value of the \t Horizontal tabulator
indexOf() specified object && Logical AND
\v Vertical tabulator
Check if an array contains the || Logical OR
includes() specified element
! Logical NOT JavaScript String Methods
Combine elements of an array into a
join() single string and return the string Return a character at a specified
Bitwise Operators charAt() position inside a string
Return a key/value pair Array Iteration & AND statement
entries() Give the unicode of character at that
Object charCodeAt()
| OR statement position
Check if every element in an array
every() passes a test ~ NOT Concatenate (join) two or more
concat() strings into one
Fill the elements in an array with a ^ XOR
fill() static value Return a string created from the
<< Left shift fromCharCode() specified sequence of UTF-16 code
Create a new array with every units
filter() element in an array that pass a test >> Right shift
Provide the position of the first
Return the value of the first element >>> Zero fill right shift indexOf() occurrence of specified text within a
find() in an array that pass a test string

forEach() Call a function for each array element


Functions Same as indexOf() but with the last
lastIndexOf() occurrence, searching backwards
from() Create an array from an object Output data in an alert box in the
alert() browser window Retrieve the matches of a string
Give the last position at which a given match() against a search pattern
lastIndexOf() Open up a yes/no dialog and return
element appears in an array confirm() true/false depending on user click Find and replace specified text in a
replace()
pop() Remove the last element of an array Write information to the browser string
push() Add a new element at the end console.log() console (good for debugging Execute a search for a matching text
purposes) search()
and return its position
reverse() Sort elements in descending order
document.write() Write directly to the HTML document Extract a section of a string and
Reduce the values of an array to a slice() return it as a new string
reduce() single value (going left-to-right) prompt() Create a dialog for user input
Split a string object into an array of
Reduce the values of an array to a Global Functions split() strings at a specified position
reduceRight() single value (going right-to-left)
Decode a Uniform Resource Identifier Check whether a string begins with
shift() Remove the first element of an array decodeURI() startsWith() specified characters
(URI) created by encodeURI or similar
Pull a copy of a portion of an array into decodeURICompo Similar to slice() but extracts a
slice() a new array object Decode a URI component
nent() substr() substring depended on a specified
number of characters
sort() Sort elements alphabetically encodeURI() Encode a URI into UTF-8
Similar to slice() but can’t accept
Add elements in a specified way and encodeURICompo substring() negative indices
splice() position Same but for URI components
nent()
toLowerCase() Convert strings to lower case
unshift() Add a new element to the beginning
Evaluate JavaScript code represented
eval() as a string toUpperCase() Convert strings to upper case
JavaScript Boolean Methods
Determine whether a passed value is Return the primitive value (that has no
Convert a Boolean value to a string, isFinite() valueOf() properties or methods) of a string
toString() a finite number
and return the result object
Determine whether a value is an
Return the first position at which a isNaN() illegal number Regular Expression Syntax
valueOf() given element appears in an array
Number() Convert an object's value to a number
Return a string representing the Pattern Modifiers
toSource() Parse a string and return a floating
source code of the object parseFloat() point number e Evaluate replacement
JavaScript Arithmetic Operators parseInt() Parse a string and return an integer i Perform case-insensitive matching
+ Addition
g Perform global matching
- Subtraction
JavaScript Loops m Perform multiple line matching
* Multiplication
The most common way to create a s Treat strings as single line
/ Division for
loop in JavaScript Allow comments and whitespace in
x pattern
Grouping operator (operations within Set up conditions under which a loop
(...) brackets are executed earlier than while executes
those outside) U Ungreedy pattern
Similar to the while loop, however, it
% Modulus (remainder) executes at least once and performs a Brackets
do while check at the end to see if the
++ Increment numbers condition is met to execute again Find any of the characters in the
[abc] brackets
-- Decrement numbers Stop and exit the cycle if certain
break [^abc] Find any character not in the brackets
== Equal to conditions are mets
[0-9] Find digit specified in the brackets
=== Equal value and equal type Skip parts of the cycle if certain
continue conditions are met Find any character from uppercase A
!= Not equal [A-z] to lowercase z
Escape Characters
!== Not equal value or not equal type Find any of the alternatives separated
(a|b|c)
\' Single quote with |
> Greater than
\" Double quote Metacharacters
< Lesser than
\\ Backslash

Copyright © 2019 MakeUseOf. For more cheat sheets, head over to www.makeuseof.com
Find a single character, except LN2 Natural logarithm of 2 setMinutes() Set the minutes (0-59)
. newline or line terminator
LN10 Natural logarithm of 10 setMonth() Set the month (0-11)
\w Word character
LOG2E Base 2 logarithm of E setSeconds() Set the seconds (0-59)
\W Non-word character
LOG10E Base 10 logarithm of E Set the time (milliseconds since
\d A digit setTime() January 1, 1970)
PI The number PI
\D A non-digit character Set the day of the month for a
SQRT1_2 Square root of 1/2 specified date according to universal
\s Whitespace character setUTCDate()
time (also available for day, month,
SQRT2 Square root of 2 fullyear, hours, minutes etc.)
\S Non-whitespace character
Find a match at the beginning/end of DOM Mode
\b
a word Math Methods
Find a match not at the beginning/end Return the absolute (positive) value of
Node Properties
\B of a word abs(x) x Live collection of all attributes
attributes registered to an element
\0 NUL character acos(x) Arccosine of x, in radians
\n A new line character Absolute base URL of an HTML
asin(x) Arcsine of x, in radians baseURI
element
\f Form feed character atan(x) Arctangent of x as a numeric value
childNodes Collection of an element’s child nodes
\r Carriage return character Arctangent of the quotient of its
atan2(y,x) arguments firstChild First child node of an element
\t Tab character
Value of x rounded up to its nearest lastChild Last child node of an element
\v Vertical tab character ceil(x) integer nextSibling Next node at the same node tree level
Character specified by an octal
\xxx number xxx cos(x) Cosine of x (x is in radians) nodeName Name of a node
Latin character specified by a exp(x) Value of Ex nodeType Type of a node
\xdd hexadecimal number dd Value of x rounded down to its nodeValue Value of a node
floor(x) nearest integer
Unicode character specified by a
\udddd hexadecimal number dddd Top-level document object for current
log(x) Natural logarithm (base E) of x ownerDocument node
max(x,y,z,...,n) Number with highest value parentNode Parent node of an element
Quantifiers min(x,y,z,...,n) Number with lowest value Node immediately preceding the
previousSibling current one
Match any string that contains at pow(x,y) X to the power of y
n+ least one n
random() Random number between 0 and 1 Textual content of a node and its
textContent descendants
Any string that contains zero or more
n* occurrences of n Value of x rounded to its nearest
round(x)
integer Node Methods
Any string that contains zero or one
n? occurrences of n sin(x) Sine of x (x is in radians) Add a new child node to an element
appendChild() as the last child node
Any string that contains a sequence sqrt(x) Square root of x
n{X} cloneNode() Clone HTML element
of X n’s tan(x) Tangent of an angle
Strings that contains a sequence of X compareDocumen Compare the document position of
n{X,Y} to Y n’s tPosition() two elements

n{X,}
Matches any string that contains a Dates getFeature()
Return an object which implements
sequence of at least X n’s the APIs of a specified feature
Create a new date object with the
n$ Any string with n at the end of it Date() current date and time Return true if an element has any
hasAttributes() attributes, else return false
^n String with n at the beginning of it Create a custom date object. The
numbers represent year, month, day, Return true if an element has any
Any string that is followed by a Date(2017, 5, 21, hasChildNodes()
?=n hour, minutes, seconds, milliseconds. child nodes, else return false
specific string n 3, 23, 10, 0)
You can omit anything you want
except for year and month. Insert a new child node before a
String that is not followed by a insertBefore() specified, existing child node
?!n specific string n Date(“2017-06-23
Date declaration as a string
”) isDefaultNamespa Return true if a specified
namespaceURI is the default, else
ce() return false
Get the day of the month as a number
Number Properties getDate() (1-31)
isEqualNode() Check if two elements are equal
Maximum numeric value getDay() Get the weekday as a number (0-6)
MAX_VALUE Check if two elements are the same
representable in JavaScript isSameNode() node
Get the year as a four digit number
getFullYear()
Smallest positive numeric value (yyyy) Return true if a specified feature is
MIN_VALUE representable in JavaScript isSupported()
getHours() Get the hour (0-23) supported on the element
NaN The “Not-a-Number” value
getMilliseconds() Get the millisecond (0-999) lookupNamespace Return the namespaceURI associated
NEGATIVE_INFINI URI() with a given node
Negative Infinity value getMinutes() Get the minute (0-59)
TY
Return a DOMString containing the
POSITIVE_INFINIT getMonth() Get the month as a number (0-11) lookupPrefix() prefix for a given namespaceURI, if
Positive Infinity value present
Y getSeconds() Get the second (0-59)
Join adjacent text nodes and remove
Number Methods Get the time (milliseconds since normalize() empty text nodes in an element
getTime() January 1, 1970)
Return a string with a rounded removeChild() Remove a child node from an element
toExponential() number written as exponential Day (date) of the month in the
notation specified date according to universal replaceChild() Replace a child node in an element
getUTCDate() time (also available for day, month,
Return string of a number with a fullyear, hours, minutes etc.)
toFixed()
specified number of decimals
Parse a string representation of a Element Methods
Return string of a number written parse date, and return the number of
toPrecision() with a specified length milliseconds since January 1, 1970 Return the specified attribute value of
getAttribute() an element node
toString() Return a number as a string setDate() Set the day as a number (1-31)
Return string value of the attribute
valueOf() Return a number as a number Set the year (optionally month and getAttributeNS() with the specified namespace and
setFullYear() day) name
Math Properties setHours() Set the hour (0-23) getAttributeNode(
Get the the specified attribute node
E Euler’s number setMilliseconds() Set the milliseconds (0-999) )

Copyright © 2019 MakeUseOf. For more cheat sheets, head over to www.makeuseof.com
getAttributeNode Return the attribute node for the top Return the topmost browser window onkeydown When user is pressing a key down
attribute with the given namespace
NS() onkeypress When user starts pressing a key
and name Browser Window Methods
getElementsByTa Provide a collection of all child onkeyup When user releases a key
Display an alert box with a message
gName() elements with the specified tag name alert() and an OK button
JavaScript Frame Events
getElementsByTa Return a live HTML collection of Remove focus from the current
elements with a certain tag name blur() window onabort When loading of media is aborted
gNameNS() belonging to the given namespace
clearInterval() Clear a timer set with setInterval() Before the document is about to be
Return true if an element has any onbeforeunload unloaded
hasAttribute() attributes, else return false clearTimeout() Clear a timer set with setTimeout()
When an error occurs while loading an
Provide a true/false value indicating close() Close the current window onerror external file
hasAttributeNS() whether the current element in a
given namespace has the specified Display a dialog box with a message When the anchor part of a URL has
confirm() and OK and Cancel buttons onhashchange changed
attribute
Remove a specified attribute from an focus() Set focus to the current window onload When an object has loaded
removeAttribute() element
Move a window relative to its current When user navigates away from a
moveBy() position onpagehide webpage
removeAttributeN Remove the specified attribute from
an element within a certain
S() moveTo() Move a window to a specified position onpageshow When user navigates to a webpage
namespace
removeAttributeN Take away a specified attribute node open() Open a new browser window onresize When user resizes document view
ode() and return the removed node Print the content of the current When user is scrolling an element’s
print() onscroll
Set or change the specified attribute window scrollbar
setAttribute() to a specified value Display a dialog box that prompts the onunload When a page has unloaded
prompt() visitor for input
Add a new attribute or change the
setAttributeNS() value of an attribute with the given Resize the window by the specified
namespace and name resizeBy() number of pixels JavaScript Form Events
Set or change the specified attribute Resize the window to a specified
setAttributeNode() node resizeTo() onblur When an element loses focus
width and height
setAttributeNode Add a new namespaced attribute When the content of a form element
Scroll the document by a specified onchange changes (for <input>, <select>and
NS() node to an element scrollBy() number of pixels
<textarea>)
Browser Window Properties Scroll the document to specified
scrollTo() onfocus When an element gets focus
coordinates
Check whether a window has been When an element is about to get
closed closed or not and return true or false Call a function or evaluate an onfocusin
setInterval() focus
expression at specified intervals
Set or return the default text in the When an element is about to lose
defaultStatus statusbar of a window Call a function or evaluate an onfocusout
setTimeout() focus
expression after a specified interval
Return the document object for the oninput User input on an element
document stop() Stop the window from loading
window
oninvalid When an element is invalid
frames
Return all <iframe> elements in the Screen Properties
current window onreset When a form is reset
Return the height of the screen
Provide the History object for the availHeight (excluding the Windows Taskbar) When a user types something in a
history onsearch search field (for <input="search">)
window
Return the width of the screen
Inner height of a window’s content availWidth (excluding the Windows Taskbar) When user selects some text (for
innerHeight onselect <input> and <textarea>)
area
Return the bit depth of the color
innerWidth Inner width of the content area colorDepth palette for displaying images onsubmit When a form is submitted

Return the number of <iframe> height The total height of the screen JavaScript Drag Events
length elements in the window
The color resolution of the screen in ondrag When user drags an element
Return the location object for the pixelDepth bits per pixel
location
window When user has finished dragging the
width The total width of the screen ondragend element
name Set or return the name of a window
When the dragged element enters a
Return the Navigator object for the ondragenter drop target
navigator window JavaScript Events
When the dragged element leaves
Return a reference to the window that ondragleave the drop target
opener created the window
JavaScript Mouse Events
When the dragged element is on top
Outer height of a window, including ondragover
outerHeight toolbars/scrollbars onclick When user clicks on an element of the drop target

Outer width of a window, including When user right-clicks on an element ondragstart When user starts to drag an element
outerWidth oncontextmenu to open a context menu
toolbars/scrollbars Dragged element is dropped on the
ondrop drop target
Number of pixels by which the When user double-clicks on an
ondblclick element
pageXOffset document has been scrolled
horizontally When user presses a mouse button
JavaScript Clipboard Events
onmousedown over an element
Number of pixels by which the When user copies content of an
pageYOffset oncopy element
document has been scrolled vertically When user moves pointer onto an
onmouseenter element
parent Parent window of the current window oncut When user cuts an element’s content

Return the Screen object for the When user moves pointer away from When user pastes content in an
screen onmouseleave onpaste
window an element element
Horizontal coordinate of the window When user moves pointer while it is
screenLeft (relative to screen)
onmousemove over an element JavaScript Media Events
screenTop Vertical coordinate of the window When user moves pointer onto an onabort When media loading is aborted
onmouseover element or one of its children
Same as screenLeft but needed for When browser can start playing
screenX oncanplay media (e.g. a file has buffered enough)
some browsers When user moves pointer away from
onmouseout an element or one of its children
When browser can play through
Same as screenTop but needed for oncanplaythrough media without stopping
screenY some browsers When user releases a mouse button
onmouseup while over an element
ondurationchange When duration of media changes
self Return the current window
onended When media has reached its end
Set or return the text in the statusbar
status of a window JavaScript Keyboard Events When an error occurs while loading an
onerror
external file

Copyright © 2019 MakeUseOf. For more cheat sheets, head over to www.makeuseof.com
onloadeddata When media data is loaded
When metadata (like dimensions and
onloadedmetadata duration) is loaded

When browser starts looking for


onloadstart
specified media
When media is paused either by user
onpause or automatically
When media has been started or is no
onplay longer paused
When media is playing after having
onplaying been paused or stopped for buffering
When browser is in the process of
onprogress downloading media
When playing speed of media
onratechange
changes
When user has finished moving/
onseeked skipping to a new position in media
onseeking When user starts moving/skipping
When browser is trying to load
onstalled unavailable media
When browser is intentionally not
onsuspend loading media
The playing position has changed (e.g.
ontimeupdate because of fast forward)
When media volume has changed
onvolumechange
(including mute)
When media has paused but is
onwaiting expected to resume (for example,
buffering)

Animation
animationend When CSS animation is complete
animationiteration When CSS animation is repeated
animationstart When CSS animation has started

Miscellaneous
transitionend When CSS transition is complete
When a message is received through
onmessage the event source
onoffline When browser starts to work offline
ononline When browser starts to work online
onpopstate When the window’s history changes
When a <menu> element is shown as
onshow a context menu
onstorage When a Web Storage area is updated
When user opens or closes the
ontoggle
<details> element
When mouse wheel rolls up or down
onwheel over an element
ontouchcancel When screen touch is interrupted
When user’s finger goes off touch
ontouchend screen
When user drags a finger across the
ontouchmove screen

Copyright © 2019 MakeUseOf. For more cheat sheets, head over to www.makeuseof.com

You might also like