Js Handbook
Js Handbook
JAVASCRIPT
CHEATSHEET
by
PAPA React
Join Zero to Full Stack Hero to learn more, visit www.papareact.com 1
J o i n Z e r o t o F u l l S ta c k H e r o , t o l e a r n m o r e v i s i t: w w w. p a p a r e a c t. c o m
Meet Sonny
Also known as PAPA React
“
To truly succeed,
“
we must get Comfortable with the Uncomfortable
St r i n g s
String Methods
charAt() charCodeAt()
The charAt() method returns the character at the The charCodeAt() method returns the Unicode of
specified index in a string. The index of the first the character at the specified index in a string.
character is 0, the second character is 1, and so on.
concat() endsWith()
The concat() method is used to join two or more The endsWith() method determines whether a
strings. This method does not change the existing string ends with the characters of a specified string.
strings, but returns a new string containing the text This method returns true if the string ends with the
of the joined strings. characters, and false if not.
fromCharCode() includes()
The fromCharCode() method converts Unicode The includes() method determines whether a string
values into characters. This is a static method of contains the characters of a specified string.
the String object, and the syntax is always String.
fromCharCode()
indexOf() lastIndexOf()
The indexOf() method returns the position of the The lastIndexOf() method returns the position of the
first occurrence of a specified value in a string. This last occurrence of a specified value in a string. The
method returns -1 if the value to search for never string is searched from the end to the beginning,
occurs. but returns the index starting at the beginning, at
position 0.
localeCompare() match()
The localeCompare() method compares two strings The match() method searches a string for a match
in the current locale. The locale is based on the against a regular expression, and returns the
language settings of the browser. matches, as an Array object.
Returns -1 if str1 is sorted before str2
Returns 0 if the two strings are equal
Returns 1 if str1 is sorted after str2
repeat() replace()
The repeat() method returns a new string with a The replace() method searches a string for a
specified number of copies of the string it was specified value, or a regular expression, and returns a
called on. new string where the specified values are replaced.
search() slice()
The search() method searches a string for a The slice() method extracts parts of a string and
specified value, and returns the position of the returns the extracted parts in a new string.
match.
split() startsWith()
The split() method is used to split a string into an The startsWith() method determines whether a string
array of substrings, and returns the new array. begins with the characters of a specified string.
substr() substring()
The substr() method extracts parts of a string, The substring() method extracts the characters from
beginning at the character at the specified position, a string, between two specified indices, and returns
and returns the specified number of characters. the new sub string.
toLocaleLowerCase() toLocaleUpperCase()
The toLocaleLowerCase() method converts a string The toLocaleUpperCase() method converts a string
to lowercase letters, according to the host’s current to uppercase letters, according to the host’s current
locale. locale.
toLowerCase() toUpperCase()
The toLowerCase() method converts a string to The toUpperCase() method converts a string to
lowercase letters. It does not change the original uppercase letters. It does not change the original
string. string.
trim()
The trim() method removes whitespace from both
sides of a string. It does not change the original string.
A r r ays
A r r ay P r o p e r t i e s
constructor length
In JavaScript, the constructor property returns the The length property sets or returns the number of
constructor function for an object. For JavaScript elements in an array.
arrays the constructor property returns function
Array() { [native code] }
prototype
The prototype constructor allows you to add new
properties and methods to the Array() object.
A r r ay M e t h o d s
concat() copyWithin()
The concat() method is used to join two or more copies array elements to another position in the
arrays. This method does not change the existing array, overwriting the existing values. This method
arrays, but returns a new array, containing the will never add more items to the array. Note: this
values of the joined arrays. method overwrites the original array.
entries() every()
The entries() method returns an Array Iterator The every() method checks if all elements in an
object with key/value pairs.. array pass a test (provided as a function).
fill() filter()
The fill() method fills the specified elements in The filter() method creates an array filled with all
an array with a static value. You can specify the array elements that pass a test (provided as a
position of where to start and end the filling. If not function).
specified, all elements will be filled.
find() findIndex()
The find() method returns the value of the first The findIndex() method returns the index of the first
element in an array that pass a test (provided as a element in an array that pass a test (provided as a
function). function).
forEach() includes()
The forEach() method calls a function once for each The includes() method determines whether an array
element in an array, in order. contains a specified element..
indexOf() isArray()
The indexOf() method searches the array for the The isArray() method determines whether an object
specified item, and returns its position. is an array.Thinction returns true if the object is an
array, and false if not.
join() lastIndexOf()
Convert the elements of an array into a string. The The lastIndexOf() method searches the array for the
join() method returns the array as a string. specified item, and returns its position.
map() pop()
The map() method creates a new array with the The pop() method removes the last element of an
results of calling a function for every array element. array, and returns that element.
push() reduce()
The push() method adds new items to the end of an The reduce() method executes a provided function
array, and returns the new length. for each value of the array (from left-to-right) and
reduces the array to a single value.
reduceRight() reverse()
The reduceRight() method executes a provided The reverse() method reverses the order of the
function for each value of the array (from right-to- elements in an array.
left) and reduces the array to a single value.
some() slice()
The some() method checks if any of the elements The slice() method selects the elements starting
in an array pass a test (provided as a function). at the given start argument, and ends at, but does
It executes the function once for each element not include, the given end argument. It returns the
present in the array selected elements in an array, as a new array object.
shift() sort()
The shift() method removes the first item of an The sort() method sorts the items of an array.
array.
splice() toString()
The splice() method adds/removes items to/from The toString() method returns a string with all the
an array, and returns the removed item(s). array values, separated by commas.
unshift() valueOf()
The unshift() method adds new items to the The valueOf() method returns the array. This
beginning of an array, and returns the new length. method is the default method of the array object.
Array.valueOf() will return the same as Array
Console Methods
console.assert() console.clear()
The console.assert() method writes a message to The console.clear() method clears the console. It
the console, but only if an expression evaluates to will also write a message in the console: “Console
false. was cleared”.
console.count() console.error()
Writes to the console the number of times that he console.error() method writes an error message
particular console.count() is called. You can add a to the console.The console is useful for testing
label that will be included in the console view. purposes.
console.group() console.groupCollapsed()
The console.group() method indicates the start of a The console.groupCollapsed() method indicates
message group.All messages will from now on be the start of a collapsed message group. Click the
written inside this group. expand button to open the message group.
console.groupEnd() console.table()
The console.groupEnd() method indicates the end of The console.table() method writes a table in the
a message group. console view. The first parameter is required, and
must be either an object, or an array, containing
data to fill the table.
console.info() console.log()
The console.info() method writes a message to the The console.log() method writes a message to the
console. console. The console is useful for testing purposes.
console.time() console.warn()
Use the console.time() method to start the timer. The console.warn() method writes a warning to the
The console.timeEnd() method ends a timer, and console.
writes the result in the console view.
stopPropagation() target
The stopPropagation() method prevents propagation The target event property returns the element that
of the same event from being called. triggered the event.
Screen Object
availHeight availWidth
The availHeight property returns the height of the The availWidth property returns the width of the
user’s screen, in pixels, minus interface features like user’s screen, in pixels, minus interface features like
the Windows Taskbar. the Windows Taskbar.
colorDepth height
The colorDepth property returns the bit depth of the The height property returns the total height of the
color palette for displaying images (in bits per pixel). user’s screen, in pixels.
pixelDepth width
The pixelDepth property returns the color resolution The width property returns the total width of the
(in bits per pixel) of the visitor’s screen. user’s screen, in pixels.
Browser Window
Window Properties
closed frameElement
The closed property returns a Boolean value The frameElement property returns the <iframe>
indicating whether a window has been closed or element in which the current window is inserted.
not.The closed property returns a Boolean value If the document window is not placed within an
indicating whether a window has been closed or not. <iframe>, the return value of this property is null.
length localStorage
The length property returns the number of <iframe> The localStorage and sessionStorage properties
elements in the current window. allow to save key/value pairs in a web browser.
name parent
The name property sets or returns the name of the The parent property returns the parent window of
window. This property is often used to modify the the current window.
name of a window,
Window Properties
alert() atob()
The alert() method displays an alert box with a The atob() method decodes a base-64 encoded
specified message and an OK button. string. This method decodes a string of data which
has been encoded by the btoa() method.
blur() btoa()
The blur() method removes focus from the current The btoa() method encodes a string in base-64.
window.
clearInterval() clearTimeout()
The clearInterval() method clears a timer set with the The clearTimeout() method clears a timer set with
setInterval() method. The ID value returned by the setTimeout() method.
setInterval() is used as the parameter for the
clearInterval() method.
close() confirm()
The close() method closes the current window. The confirm() method displays a dialog box with a
specified message, along with an OK and a Cancel
button.
focus() getSelection()
The focus() method sets focus to the current Returns a Selection object representing the range
window. of text selected by the user
getComputedStyle() matchMedia()
The getComputedStyle() method gets all the actual The window.matchMedia() method returns a
(computed) CSS property and values of the specified MediaQueryList object representing the results of
element. the specified CSS media query string.
moveBy() moveTo()
The moveBy() method moves a window a specified The moveTo() method moves a window’s left and
number of pixels relative to its current coordinates. top edge to the specified coordinates.
open() print()
The open() method opens a new browser window, or The print() method opens the Print Dialog Box,
a new tab, depending on your browser settings and which lets the user to select preferred printing
the parameter values. options.
prompt() resizeBy()
The prompt() method displays a dialog box that The resizeBy() method resizes a window by the
prompts the visitor for input. specified amount, relative to its current size.
resizeTo() scrollBy()
The resizeTo() method resizes a window to the The scrollBy() method scrolls the document by the
specified width and height. specified number of pixels.
scrollTo() setInterval()
The scrollTo() method scrolls the document to the The setInterval() method calls a function or
specified coordinates. evaluates an expression at specified intervals (in
milliseconds).
setTimeout() stop()
The setTimeout() method calls a function or The stop() method stops window loading.
evaluates an expression after a specified number of
milliseconds.
baseURI body
The baseURI property returns the base URI of the The body property sets or returns the document’s
HTML document. This property is read-only. body.
close() cookie
The close() method closes the output stream The cookie property sets or returns all name/value
previously opened with the document.open() method pairs of cookies in the current document.
characterSet createComment()
The characterSet property returns the character The createComment() method creates a Comment
encoding for the document. node with the specified text.
createAttribute() createDocumentFragment()
The createAttribute() method creates an attribute The createDocumentFragment() method creates an
with the specified name, and returns the attribute as imaginary Node object, with all the properties and
an Attr object. methods of the Node object.
createElement() createEvent()
The createElement() method creates an Element The createDocumentFragment() method creates an
Node with the specified name.The createElement() imaginary Node object, with all the properties and
method creates an Element Node with the specified methods of the Node object.
name.
createTextNode() createComment()
The createTextNode() method creates a Text Node The createComment() method creates a Comment
with the specified text. node with the specified text.
defaultView designMode
The defaultView property returns the document’s The designMode property sets or returns whether
Window Object. the document is editable or not.
documentElement documentURI
The documentElement property returns the The documentURI property sets or returns the
documentElement of the document, as an Element location of a document. If the document was
object. For HTML documents the returned object is created by the DocumentImplementation object, or
the <html> element. if it is undefined, the return value is null.
domain embeds
The domain property returns the domain name of the The embeds collection returns a collection of all
server that loaded the current document. <embeds> elements in the document.
execCommand() forms
The execCommand() method executes the specified The forms collection returns a collection of all
command for the selected part of an editable <form> elements in the document.
section.
fullscreenElement fullscreenEnabled()
The fullscreenElement property returns the current The fullscreenEnabled() method returns a Boolean
element that is displayed in fullscreen mode, or null value indicating whether the document can be
when not in fullscreen. viewed in fullscreen mode.
getElementById() getElementsByClassName()
The getElementById() method returns the element The getElementsByClassName() method returns a
that has the ID attribute with the specified value. collection of all elements in the document with the
specified class name
getElementsByName() getElementsByTagName()
The getElementsByName() method returns a The getElementsByTagName() method returns a
collection of all elements in the document with the collection of all elements in the document with the
specified name (the value of the name attribute) specified tag name, as an HTMLCollection object.
hasFocus() head
The hasFocus() method returns a Boolean value The head property returns the <head> element of
indicating whether the document (or any element the current document.
inside the document) has focus.
images implementation
The images collection returns a collection of all The implementation property returns the
<img> elements in the document. DOMimplementation object that handles this
document, as a DocumentImplementation object.
inputEncoding lastModified
The inputEncoding property returns the character The lastModified property returns the date and time
encoding for the document. the current document was last modified.
links normalize()
The links collection returns a collection of all links in The normalize() method removes empty Text nodes,
the document. and joins adjacent Text nodes.
normalizeDocument() open()
The normalizeDocument() method removes empty The open() method opens an output stream to
Text nodes, and joins adjacent Text nodes. collect the output from any document.write() or
document.writeln() methods.
querySelector querySelectorAll()
The normalizeDocument() method removes empty The querySelectorAll() method returns all elements
Text nodes, and joins adjacent Text nodes. in the document that matches a specified CSS
selector(s), as a static NodeList object.
readyState referrer
The readyState property returns the (loading) status The referrer property returns the URL of the
of the current document. document that loaded the current document.
removeEventListener() scripts
The document.removeEventListener() method The scripts collection returns a collection of all
removes an event handler that has been attached <script> elements in the document.
with the document.addEventListener() method.
title URL
The title property sets or returns the title of the The URL property returns the full URL of the current
current document (the text inside the HTML title HTML document.
element).
write() writeln()
The write() method writes HTML expressions or The writeln() method is identical to the document.
JavaScript code to a document. write() method, with the addition of writing a
newline character after each statement.
History Object
length back()
The length property returns the number of URLs in The back() method loads the previous URL in the
the history list of the current browser window. history list.
forward() go()
The forward() method loads the next URL in the The go() method loads a specific URL from the
history list. history list.
Navigator Object
appCodeName appName
The appCodeName property returns the code name The appName property returns the name of the
of the browser. browser.
appVersion cookieEnabled
The appVersion property returns the version The cookieEnabled property returns a Boolean value
information of the browser. that specifies whether cookies are enabled in the
browser.
geolocation language
The geolocation property returns a Geolocation The language property returns the language version
object that can be used to locate the user’s position. of the browser.
onLine product
The onLine property returns a Boolean value that The product property returns the engine (product)
specifies whether the browser is in online or offline name of the browser.
mode.
userAgent platform
The userAgent property returns the value of the The platform property returns for which platform
user-agent header sent by the browser to the server. the browser is compiled.
Geolocation Object
coordinates position
The coordinates property returns the position and The position property returns the position and altitude
altitude of the device on Earth. of the device on Earth.
positionError positionOptions
Returns the reason of an error occurring when using Describes an object containing option properties
the geolocating device to pass as a parameter of Geolocation.
getCurrentPosition() and Geolocation.watchPosition()
clearWatch()
Unregister location/error monitoring handlers getCurrentPosition()
previously installed using Geolocation. Returns the current position of the device
watchPosition()
watchPosition()
Returns a watch ID value that then can be used to
unregister the handler by passing it to the
Geolocation.- clearWatch() method
Location Object
hash host
The hash property sets or returns the anchor part of The host property sets or returns the hostname and
a URL, including the hash sign (#). port of a URL.
hostname href
The hostname property sets or returns the hostname The href property sets or returns the entire URL of
of a URL. the current page.
origin pathname
The origin property returns the protocol, hostname The pathname property sets or returns the
and port number of a URL. pathname of a URL.
port search
The port property sets or returns the port number The search property sets or returns the querystring
the server uses for a URL. part of a URL, including the question mark (?).
assign() reload()
The assign() method loads a new document. The reload() method is used to reload the current
document.
replace()
The replace() method replaces the current document
with a new one.
animationend animationiteration
The animationend event occurs when a CSS The animationiteration event occurs when a CSS
animation has completed. animation is repeated.
animationstart beforeprint
The animationstart event occurs when a CSS The beforeprint event occurs when a page is about to
animation has started to play. be printed (before the print dialogue box appears).
beforeunload blur
The onbeforeunload event occurs when the The onblur event occurs when an object loses
document is about to be unloaded. focus. The onblur event is most often used with
form validation code (e.g. when the user leaves a
form field).
canplay canplaythrough
The oncanplay event occurs when the browser can The oncanplaythrough event occurs when the
start playing the specified audio/video (when it has browser estimates it can play through the specified
buffered enough to begin). media without having to stop for buffering.
change click
The onchange event occurs when the value of an The onclick event occurs when the user clicks on an
element has been changed. element.
contextmenu copy
The oncontextmenu event occurs when the user The oncopy event occurs when the user copies the
right-clicks on an element to open the context menu. content of an element.
cut dblclick
The oncut event occurs when the user cuts the The ondblclick event occurs when the user double-
content of an element. clicks on an element.
drag dragend
The ondrag event occurs when an element or text The ondragend event occurs when the user has
selection is being dragged. finished dragging an element or text selection.
dragenter dragleave
The ondragenter event occurs when a draggable The ondragleave event occurs when a draggable
element or text selection enters a valid drop target. element or text selection leaves a valid drop target.
dragover dragstart
The ondragover event occurs when a draggable The ondragstart event occurs when the user starts
element or text selection is being dragged over a to drag an element or text selection.
valid drop target.
drop durationchange
The ondrop event occurs when a draggable element The ondurationchange event occurs when the
or text selection is dropped on a valid drop target. duration of the audio/video is changed.
ended error
The onended event occurs when the audio/video has The onerror event is triggered if an error occurs while
reached the end. loading an external file (e.g. a document or an
image).
focus focusin
The onfocus event occurs when an element gets The onfocusin event occurs when an element is
focus. The onfocus event is most often used with about to get focus.
<input>, <select>, and <a>.
focusout fullscreenchange
The onfocusout event occurs when an element is The fullscreenchange event occurs when an element
about to lose focus. is viewed in fullscreen mode.
fullscreenerror hashchange
The fullscreenerror event occurs when an element The onhashchange event occurs when there has
can not be viewed in fullscreen mode, even if it has been changes to the anchor part (begins with a ‘#’
been requested. symbol) of the current URL.
input invalid
The oninput event occurs when an element gets user The oninvalid event occurs when a submittable
input. This event occurs when the value of an <input> element is invalid.
<input> or <textarea> element is changed.
keydown keypress
The onkeydown event occurs when the user is The onkeypress event occurs when the user presses
pressing a key (on the keyboard). a key (on the keyboard).
keyup load
The onkeyup event occurs when the user releases a The onload event occurs when an object has been
key (on the keyboard). loaded.
loadeddata loadedmetadata
The onloadeddata event occurs when data for the The onloadedmetadata event occurs when meta
current frame is loaded, but not enough data to play data for the specified audio/video has been loaded.
next frame of the specified audio/video.
loadstart message
The onloadstart event occurs when the browser The onmessage event occurs when a message is
starts looking for the specified audio/video. This is received through an event source.
when the loading process starts.
mousedown mouseenter
The onmousedown event occurs when a user The onmouseenter event occurs when the mouse
presses a mouse button over an element. pointer is moved onto an element.
mouseleave mousemove
The onmouseleave event occurs when the mouse The onmousemove event occurs when the pointer
pointer is moved out of an element. is moving while it is over an element.
mouseover mouseout
The onmouseover event occurs when the mouse The onmouseout event occurs when the mouse
pointer is moved onto an element, or onto one of its pointer is moved out of an element, or out of one of
children. its children.
mouseup offline
The onmouseup event occurs when a user releases a The onoffline event occurs when the browser starts
mouse button over an element. to work offline.
online open
The ononline event occurs when the browser starts The onopen event occurs when a connection with
to work online. an event source is opened.
pagehide pageshow
The onpagehide event occurs when the user is The onpageshow event occurs when a user
navigating away from a webpage. navigates to a webpage.
paste pause
The onpaste event occurs when the user pastes The onpause event occurs when the audio/video is
some content in an element. paused either by the user or programmatically.
play playing
The onplay event occurs when the audio/video has The onplaying event occurs when the audio/video is
been started or is no longer paused. playing after having been paused or stopped for
buffering.
progress ratechange
The onprogress event occurs when the browser is The onratechange event occurs when the playing
downloading the specified audio/video. speed of the audio/video is changed
resize reset
The onresize event occurs when the browser window The onreset event occurs when a form is reset.
has been resized.
scroll seeked
The onscroll event occurs when an element’s The onseeked event occurs when the user is
scrollbar is being scrolled. finished moving/skipping to a new position in the
audio/video
seeking select
The onseeking event occurs when the user starts The onselect event occurs after some text has been
moving/skipping to a new position in the audio/video. selected in an element.
show stalled
The onshow event occurs when a <menu> element is The onstalled event occurs when the browser is
shown as a context menu. trying to get media data, but data is not available.
submit suspend
The onsubmit event occurs when a form is submitted. The onsuspend event occurs when the browser is
intentionally not getting media data.
timeupdate toggle
The ontimeupdate event occurs when the playing The ontoggle event occurs when the user opens or
position of an audio/video has changed. closes the <details> element.
touchcancel touchend
The touchcancel event occurs when the touch event The touchend event occurs when the user removes
gets interrupted. the finger from an element.
touchmove touchstart
The touchmove event occurs when the user moves The touchstart event occurs when the user touches
the finger across the screen. an element.
transitionend unload
The transitionend event occurs when a CSS The onunload event occurs once a page has
transition has completed. unloaded (or the browser window has been closed).
volumechange waiting
The onvolumechange event occurs each time the The onwaiting event occurs when the video stops
volume of a video/audio has been changed. because it needs to buffer the next frame.
wheel
The onwheel event occurs when the mouse wheel is
rolled up or down over an element.