Below you can find Javascript cheat sheet in .pdf as well as in text.
JavaScript Basics
Let’s start off with the basics – how to include JavaScript in a website.
Including JavaScript in an HTML Page
To include JavaScript inside a page, you need to wrap it in <script>
tags:
<script type="text/javascript"> //JS code goes here </script>
With this input, the browser can identify and execute the code properly.
Call an External JavaScript File
You can also place JavaScript in its own file and name it inside your HTML. That way, you can keep different types of code separate from one another, making for better-organized files. If your code is in a file called myscript.js
, you would call it:
<script src="myscript.js"></script><code></code>
Including Comments
Comments are important because they help other people understand what is going on in your code or remind you if you forgot something yourself. Keep in mind that they have to be marked properly so the browser won’t try to execute them.
In JavaScript you have two different options:
- Single-line comments — To include a comment that is limited to a single line, precede it with
//
- Multi-line comments — In case you want to write longer comments between several lines, wrap it in
/*
and*/
to avoid it from being executed
Variables in JavaScript
Variables are stand-in values that you can use to perform operations. You should be familiar with them from math class.
var, const, let
You have three different possibilities for declaring a variable in JavaScript, each with their own specialties:
var
— The most common variable. Can be reassigned but only accessed within a function. Variables defined withvar
move to the top when the code is executed.const
— Can not be reassigned and not accessible before they appear within the code.let
— Similar toconst
, thelet
variable can be reassigned but not re-declared.
Data Types
Variables can contain different types of values and data types. You use =
to assign them:
- Numbers —
var age = 23
- Variables —
var x
- Text (strings) —
var a = "init"
- Operations —
var b = 1 + 2 + 3
- True or false statements —
var c = true
- Constant numbers —
const PI = 3.14
- Objects —
var name = {firstName:"John", lastName:"Doe"}
There are more possibilities. Note that variables are case sensitive. That means lastname
and lastName
will be handled as two different variables.
Objects
Objects are certain kind of variables. They are variables which can have their own values and methods. The latter are actions that you can perform on objects.
- var person = {
- firstName:"John",
- lastName:"Doe",
- age:20,
- nationality:"German"
- };
The Next Level: Arrays
Next up in our JavaScript cheat sheet are arrays. Arrays are part of many different programming languages. They are a way of organizing variables and properties into groups. Here’s how to create one in JavaScript:
- var fruit = ["Banana", "Apple", "Pear"];
Now you have an array called fruit
which contains three items that you can use for future operations.
Array Methods
Once you have created arrays, there are a few things you can do with them:
concat()
— Join several arrays into oneindexOf()
— Returns the first position at which a given element appears in an arrayjoin()
— Combine elements of an array into a single string and return the stringlastIndexOf()
— Gives the last position at which a given element appears in an arraypop()
— Removes the last element of an arraypush()
— Add a new element at the endreverse()
— Sort elements in a descending ordershift()
— Remove the first element of an arrayslice()
— Pulls a copy of a portion of an array into a new arraysort()
— Sorts elements alphabeticallysplice()
— Adds elements in a specified way and positiontoString()
— Converts elements to stringsunshift()
—Adds a new element to the beginningvalueOf()
— Returns the primitive value of the specified object
Operators
If you have variables, you can use them to perform different kinds of operations. To do so, you need operators.
Basic Operators
+
— Addition-
— Subtraction*
— Multiplication/
— Division(...)
— Grouping operator, operations within brackets are executed earlier than those outside%
— Modulus (remainder )++
— Increment numbers--
— Decrement numbers
Comparison Operators
==
— Equal to===
— Equal value and equal type!=
— Not equal!==
— Not equal value or not equal type>
— Greater than<
— Less than>=
— Greater than or equal to<=
— Less than or equal to?
— Ternary operator
Logical Operators
&&
— Logical and||
— Logical or!
— Logical not
Bitwise Operators
&
— AND statement|
— OR statement~
— NOT^
— XOR<<
— Left shift>>
— Right shift>>>
— Zero fill right shift
Functions
JavaScript functions are blocks of code which perform a certain task. A basic function looks like this:
- function name(parameter1, parameter2, parameter3) {
- // what the function does
- }
As you can see, it consists the function
keyword plus a name. The function’s parameters are in the brackets and you have curly brackets around what the function performs. You can create your own, but to make your life easier – there are also a number of default functions.
Outputting Data
A common application for functions is the output of data. For the output, you have the following options:
alert()
— Output data in an alert box in the browser windowconfirm()
— Opens up a yes/no dialog and returns true/false depending on user clickconsole.log()
— Writes information to the browser console, good for debugging purposesdocument.write()
— Write directly to the HTML documentprompt()
— Creates a dialogue for user input
Global Functions
Global functions are functions built into every browser capable of running JavaScript.
decodeURI()
— Decodes a Uniform Resource Identifier (URI) created byencodeURI
or similardecodeURIComponent()
— Decodes a URI componentencodeURI()
— Encodes a URI into UTF-8encodeURIComponent()
— Same but for URI componentseval()
— Evaluates JavaScript code represented as a stringisFinite()
— Determines whether a passed value is a finite numberisNaN()
— Determines whether a value is NaN or notNumber()
—- Returns a number converted from its argumentparseFloat()
— Parses an argument and returns a floating point numberparseInt()
— Parses its argument and returns an integer
JavaScript Loops
Loops are part of most programming languages. They allow you to execute blocks of code desired number of times with different values:
for (before loop; condition for loop; execute after loop) {
// what to do during the loop
}
You have several parameters to create loops:
for
— The most common way to create a loop in JavaScriptwhile
— Sets up conditions under which aloop executesdo while
— Similar to thewhile
loop but it executes at least once and performs a check at the end to see if the condition is met to execute againbreak
—Used to stop and exit the cycle at certain conditionscontinue
— Skip parts of the cycle if certain conditions are met
If – Else Statements
These types of statements are easy to understand. Using them, you can set conditions for when your code is executed. If certain conditions apply, something is done, if not – something else is executed.
if (condition) {
// what to do if condition is met
} else {
// what to do if condition is not met
}
A similar concept to if else
is the switch
statement. However, using the switch you select one of several code blocks to execute.
Strings
Strings are what JavaScript calls text that does not perform a function but can appear on the screen.
- var person = "John Doe";
In this case, John Doe
is the string.
Escape Characters
In JavaScript, strings are marked with single or double quotes. If you want to use quotation marks in a string, you need to use special characters:
\'
— Single quote\"
— Double quote
Aside from that you also have additional escape characters:
\\
— Backslash\b
— Backspace\f
— Form feed\n
— New line\r
— Carriage return\t
— Horizontal tabulator\v
— Vertical tabulator
String Methods
There are many different ways to work with strings:
charAt()
— Returns a character at a specified position inside a stringcharCodeAt()
— Gives you the unicode of a character at that positionconcat()
— Concatenates (joins) two or more strings into onefromCharCode()
— Returns a string created from the specified sequence of UTF-16 code unitsindexOf()
— Provides the position of the first occurrence of a specified text within a stringlastIndexOf()
— Same asindexOf()
but with the last occurrence, searching backwardmatch()
— Retrieves the matches of a string against a search patternreplace()
— Find and replace specified text in a stringsearch()
— Executes a search for a matching text and returns its positionslice()
— Extracts a section of a string and returns it as a new stringsplit()
— Splits a string object into an array of strings at a specified positionsubstr()
— Similar toslice()
but extracts a substring depending on a specified number of characterssubstring()
— Also similar toslice()
but can’t accept negative indicestoLowerCase()
— Convert strings to lower casetoUpperCase()
— Convert strings to upper casevalueOf()
— Returns the primitive value (that has no properties or methods) of a string object
Regular Expression Syntax
Regular expressions are search patterns used to match character combinations in strings. The search pattern can be used for text search and text replace operations.
Pattern Modifiers
e
— Evaluate replacementi
— Perform case-insensitive matchingg
— Perform global matchingm
— Perform multiple line matchings
— Treat strings as a single linex
— Allow comments and whitespace in the patternU
— Ungreedy pattern
Brackets
[abc]
— Find any of the characters between the brackets[^abc]
— Find any character which are not in the brackets[0-9]
— Used to find any digit from 0 to 9[A-z]
— Find any character from uppercase A to lowercase z(a|b|c)
— Find any of the alternatives separated with|
Metacharacters
.
— Find a single character, except newline or line terminator\w
— Word character\W
— Non-word character\d
— A digit\D
— A non-digit character\s
— Whitespace character\S
— Non-whitespace character\b
— Find a match at the beginning/end of a word\B
— A match not at the beginning/end of a word\0
— NUL character\n
— A new line character\f
— Form feed character\r
— Carriage return character\t
— Tab character\v
— Vertical tab character\xxx
— The character specified by an octal number xxx\xdd
— Character specified by a hexadecimal number dd\uxxxx
— The Unicode character specified by a hexadecimal number xxxx
Quantifiers
n+
— Matches any string that contains at least one nn*
— Any string that contains zero or more occurrences of nn?
— A string that contains zero or one occurrence of nn{X}
— String that contains a sequence of X n’sn{X,Y}
— Strings that contain a sequence of X to Y n’sn{X,}
— Matches any string that contains a sequence of at least X n’sn$
— Any string with n at the end of it^n
— String with n at the beginning of it?=n
— Any string that is followed by a specific string n?!n
— String that is not followed by a specific string ni
Numbers and Math
In JavaScript, you can also work with numbers, constants and perform mathematical functions.
Number Properties
MAX_VALUE
— The maximum numeric value representable in JavaScriptMIN_VALUE
— Smallest positive numeric value representable in JavaScriptNaN
— The “Not-a-Number” valueNEGATIVE_INFINITY
— The negative Infinity valuePOSITIVE_INFINITY
— Positive Infinity value
Number Methods
toExponential()
— Returns the string with a rounded number written as exponential notationtoFixed()
— Returns the string of a number with a specified number of decimalstoPrecision()
— String of a number written with a specified lengthtoString()
— Returns a number as a stringvalueOf()
— Returns a number as a number
Math Properties
E
— Euler’s numberLN2
— The natural logarithm of 2LN10
— Natural logarithm of 10LOG2E
— Base 2 logarithm of ELOG10E
— Base 10 logarithm of EPI
— The number PISQRT1_2
— Square root of 1/2SQRT2
— The square root of 2
Math Methods
abs(x)
— Returns the absolute (positive) value of xacos(x)
— The arccosine of x, in radiansasin(x)
— Arcsine of x, in radiansatan(x)
— The arctangent of x as a numeric valueatan2(y,x)
— Arctangent of the quotient of its argumentsceil(x)
— Value of x rounded up to its nearest integercos(x)
— The cosine of x (x is in radians)exp(x)
— Value of Exfloor(x)
— The value of x rounded down to its nearest integerlog(x)
— The natural logarithm (base E) of xmax(x,y,z,...,n)
— Returns the number with the highest valuemin(x,y,z,...,n)
— Same for the number with the lowest valuepow(x,y)
— X to the power of yrandom()
— Returns a random number between 0 and 1round(x)
— The value of x rounded to its nearest integersin(x)
— The sine of x (x is in radians)sqrt(x)
— Square root of xtan(x)
— The tangent of an angle
Dealing with Dates in JavaScript
You can also work with and modify dates and time with JavaScript. This is the next chapter in the JavaScript cheat sheet.
Setting Dates
Date()
— Creates a new date object with the current date and timeDate(2017, 5, 21, 3, 23, 10, 0)
— Create a custom date object. The numbers represent a year, month, day, hour, minutes, seconds, milliseconds. You can omit anything you want except for year and month.Date("2017-06-23")
— Date declaration as a string
Pulling Date and Time Values
getDate()
— Get the day of the month as a number (1-31)getDay()
— The weekday as a number (0-6)getFullYear()
— Year as a four-digit number (yyyy)getHours()
— Get the hour (0-23)getMilliseconds()
— The millisecond (0-999)getMinutes()
— Get the minute (0-59)getMonth()
— Month as a number (0-11)getSeconds()
— Get the second (0-59)getTime()
— Get the milliseconds since January 1, 1970getUTCDate()
— The day (date) of the month in the specified date according to universal time (also available for day, month, full year, hours, minutes etc.)parse
— Parses a string representation of a date and returns the number of milliseconds since January 1, 1970
Set Part of a Date
setDate()
— Set the day as a number (1-31)setFullYear()
— Sets the year (optionally month and day)setHours()
— Set the hour (0-23)setMilliseconds()
— Set milliseconds (0-999)setMinutes()
— Sets the minutes (0-59)setMonth()
— Set the month (0-11)setSeconds()
— Sets the seconds (0-59)setTime()
— Set the time (milliseconds since January 1, 1970)setUTCDate()
— Sets the day of the month for a specified date according to universal time (also available for day, month, full year, hours, minutes etc.)
DOM Mode
The DOM is the Document Object Model of a page. It is the code of the structure of a webpage. JavaScript comes with a lot of different ways to create and manipulate HTML elements (called nodes).
Node Properties
attributes
— Returns a live collection of all attributes registered to an elementbaseURI
— Provides the absolute base URL of an HTML elementchildNodes
— Gives a collection of an element’s child nodesfirstChild
— Returns the first child node of an elementlastChild
— The last child node of an elementnextSibling
— Gives you the next node at the same node tree levelnodeName
—Returns the name of a nodenodeType
— Returns the type of a nodenodeValue
— Sets or returns the value of a nodeownerDocument
— The top-level document object for this nodeparentNode
— Returns the parent node of an elementpreviousSibling
— Returns the node immediately preceding the current onetextContent
— Sets or returns the textual content of a node and its descendants
Node Methods
appendChild()
— Adds a new child node to an element as the last child nodecloneNode()
— Clones an HTML elementcompareDocumentPosition()
— Compares the document position of two elementsgetFeature()
— Returns an object which implements the APIs of a specified featurehasAttributes()
— Returns true if an element has any attributes, otherwise falsehasChildNodes()
— Returns true if an element has any child nodes, otherwise falseinsertBefore()
— Inserts a new child node before a specified, existing child nodeisDefaultNamespace()
— Returns true if a specified namespaceURI is the default, otherwise falseisEqualNode()
— Checks if two elements are equalisSameNode()
— Checks if two elements are the same nodeisSupported()
— Returns true if a specified feature is supported on the elementlookupNamespaceURI()
— Returns the namespace URI associated with a given nodelookupPrefix()
— Returns a DOMString containing the prefix for a given namespace URI, if presentnormalize()
— Joins adjacent text nodes and removes empty text nodes in an elementremoveChild()
— Removes a child node from an elementreplaceChild()
— Replaces a child node in an element
Element Methods
getAttribute()
— Returns the specified attribute value of an element nodegetAttributeNS()
— Returns string value of the attribute with the specified namespace and namegetAttributeNode()
— Gets the specified attribute nodegetAttributeNodeNS()
— Returns the attribute node for the attribute with the given namespace and namegetElementsByTagName()
— Provides a collection of all child elements with the specified tag namegetElementsByTagNameNS()
— Returns a live HTMLCollection of elements with a certain tag name belonging to the given namespacehasAttribute()
— Returns true if an element has any attributes, otherwise falsehasAttributeNS()
— Provides a true/false value indicating whether the current element in a given namespace has the specified attributeremoveAttribute()
— Removes a specified attribute from an elementremoveAttributeNS()
— Removes the specified attribute from an element within a certain namespaceremoveAttributeNode()
— Takes away a specified attribute node and returns the removed nodesetAttribute()
— Sets or changes the specified attribute to a specified valuesetAttributeNS()
— Adds a new attribute or changes the value of an attribute with the given namespace and namesetAttributeNode()
— Sets or changes the specified attribute nodesetAttributeNodeNS()
— Adds a new namespaced attribute node to an element
Working with the User Browser
Besides HTML elements, JavaScript is also able to take into account the user browser and incorporate its properties into the code.
Window Properties
closed
— Checks whether a window has been closed or not and returns true or falsedefaultStatus
— Sets or returns the default text in the status bar of a windowdocument
— Returns the document object for the windowframes
— Returns all<iframe>
elements in the current windowhistory
— Provides the History object for the windowinnerHeight
— The inner height of a window’s content areainnerWidth
— The inner width of the content arealength
— Find out the number of<iframe>
elements in the windowlocation
— Returns the location object for the windowname
— Sets or returns the name of a windownavigator
— Returns the Navigator object for the windowopener
— Returns a reference to the window that created the windowouterHeight
— The outer height of a window, including toolbars/scrollbarsouterWidth
— The outer width of a window, including toolbars/scrollbarspageXOffset
— Number of pixels the current document has been scrolled horizontallypageYOffset
— Number of pixels the document has been scrolled verticallyparent
— The parent window of the current windowscreen
— Returns the Screen object for the windowscreenLeft
— The horizontal coordinate of the window (relative to the screen)screenTop
— The vertical coordinate of the windowscreenX
— Same asscreenLeft
but needed for some browsersscreenY
— Same asscreenTop
but needed for some browsersself
— Returns the current windowstatus
— Sets or returns the text in the status bar of a windowtop
— Returns the topmost browser window
Window Methods
alert()
— Displays an alert box with a message and an OK buttonblur()
— Removes focus from the current windowclearInterval()
— Clears a timer set withsetInterval()
clearTimeout()
— Clears a timer set withsetTimeout()
close()
— Closes the current windowconfirm()
— Displays a dialogue box with a message and an OK and Cancel buttonfocus()
— Sets focus to the current windowmoveBy()
— Moves a window relative to its current positionmoveTo()
— Moves a window to a specified positionopen()
— Opens a new browser windowprint()
— Prints the content of the current windowprompt()
— Displays a dialogue box that prompts the visitor for inputresizeBy()
— Resizes the window by the specified number of pixelsresizeTo()
— Resizes the window to a specified width and heightscrollBy()
— Scrolls the document by a specified number of pixelsscrollTo()
— Scrolls the document to specified coordinatessetInterval()
— Calls a function or evaluates an expression at specified intervalssetTimeout()
— Calls a function or evaluates an expression after a specified intervalstop()
— Stops the window from loading
Screen Properties
availHeight
— Returns the height of the screen (excluding the Windows Taskbar)availWidth
— Returns the width of the screen (excluding the Windows Taskbar)colorDepth
— Returns the bit depth of the color palette for displaying imagesheight
— The total height of the screenpixelDepth
— The color resolution of the screen in bits per pixelwidth
— The total width of the screen
JavaScript Events
Events are things that can happen to HTML elements and are performed by the user. The programming language can listen for these events and trigger actions in the code. No JavaScript cheat sheet would be complete without them.
Mouse
onclick
— The event occurs when the user clicks on an elementoncontextmenu
— User right-clicks on an element to open a context menuondblclick
— The user double-clicks on an elementonmousedown
— User presses a mouse button over an elementonmouseenter
— The pointer moves onto an elementonmouseleave
— Pointer moves out of an elementonmousemove
— The pointer is moving while it is over an elementonmouseover
— When the pointer is moved onto an element or one of its childrenonmouseout
— User moves the mouse pointer out of an element or one of its childrenonmouseup
— The user releases a mouse button while over an element
Keyboard
onkeydown
— When the user is pressing a key downonkeypress
— The moment the user starts pressing a keyonkeyup
— The user releases a key
Frame
onabort
— The loading of a media is abortedonbeforeunload
— Event occurs before the document is about to be unloadedonerror
— An error occurs while loading an external fileonhashchange
— There have been changes to the anchor part of a URLonload
— When an object has loadedonpagehide
— The user navigates away from a webpageonpageshow
— When the user navigates to a webpageonresize
— The document view is resizedonscroll
— An element’s scrollbar is being scrolledonunload
— Event occurs when a page has unloaded
Form
onblur
— When an element loses focusonchange
— The content of a form element changes (for<input>
,<select>
and<textarea>
)onfocus
— An element gets focusonfocusin
— When an element is about to get focusonfocusout
— The element is about to lose focusoninput
— User input on an elementoninvalid
— An element is invalidonreset
— A form is resetonsearch
— The user writes something in a search field (for<input="search">
)onselect
— The user selects some text (for<input>
and<textarea>
)onsubmit
— A form is submitted
Drag
ondrag
— An element is draggedondragend
— The user has finished dragging the elementondragenter
— The dragged element enters a drop targetondragleave
— A dragged element leaves the drop targetondragover
— The dragged element is on top of the drop targetondragstart
— User starts to drag an elementondrop
— Dragged element is dropped on the drop target
Clipboard
oncopy
— User copies the content of an elementoncut
— The user cuts an element’s contentonpaste
— A user pastes content in an element
Media
onabort
— Media loading is abortedoncanplay
— The browser can start playing media (e.g. a file has buffered enough)oncanplaythrough
— The browser can play through media without stoppingondurationchange
— The duration of the media changesonended
— The media has reached its endonerror
— Happens when an error occurs while loading an external fileonloadeddata
— Media data is loadedonloadedmetadata
— Metadata (like dimensions and duration) are loadedonloadstart
— The browser starts looking for specified mediaonpause
— Media is paused either by the user or automaticallyonplay
— The media has been started or is no longer pausedonplaying
— Media is playing after having been paused or stopped for bufferingonprogress
— The browser is in the process of downloading the mediaonratechange
— The playing speed of the media changesonseeked
— User is finished moving/skipping to a new position in the mediaonseeking
— The user starts moving/skippingonstalled
— The browser is trying to load the media but it is not availableonsuspend
— The browser is intentionally not loading mediaontimeupdate
— The playing position has changed (e.g. because of fast forward)onvolumechange
— Media volume has changed (including mute)onwaiting
— Media paused but expected to resume (for example, buffering)
Animation
animationend
— A CSS animation is completeanimationiteration
— CSS animation is repeatedanimationstart
— CSS animation has started
Other
transitionend
— Fired when a CSS transition has completedonmessage
— A message is received through the event sourceonoffline
— The browser starts to work offlineononline
— The browser starts to work onlineonpopstate
— When the window’s history changesonshow
— A<menu>
element is shown as a context menuonstorage
— A Web Storage area is updatedontoggle
— The user opens or closes the<details>
elementonwheel
— Mouse wheel rolls up or down over an elementontouchcancel
— Screen-touch is interruptedontouchend
— User’s finger is removed from a touch-screenontouchmove
— A finger is dragged across the screenontouchstart
— A finger is placed on the touch-screen
Errors
When working with JavaScript, different errors can occur. There are several ways of handling them:
try
— Lets you define a block of code to test for errorscatch
— Set up a block of code to execute in case of an errorthrow
— Create custom error messages instead of the standard JavaScript errorsfinally
— Lets you execute code, after try and catch, regardless of the result
Error Name Values
JavaScript also has a built-in error object. It has two properties:
name
— Sets or returns the error namemessage
— Sets or returns an error message in string from
The error property can return six different values as its name:
EvalError
— An error has occurred in theeval()
functionRangeError
— A number is “out of range”ReferenceError
— An illegal reference has occurredSyntaxError
— A syntax error has occurredTypeError
— A type error has occurredURIError
— AnencodeURI()
error has occurred
The JavaScript Cheat Sheet in a Nutshell
JavaScript is gaining much importance as a programming language. It is increasingly the go-to language for building web properties thanks to its proven track record and benefits.
In the JavaScript cheat sheet above, we have compiled many of the most basic and important operators, functions, principles, and methods. It provides a good overview of the language and a reference for both developers and learners. We hope you have found it useful.