JavaScript Cheat Sheet
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. It can be reassigned but only accessed within a function. Variables defined withvarmove 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, theletvariable 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 = 23Variables β
var xText (strings) β
var a = "init"Operations β
var b = 1 + 2 + 3True or false statements β
var c = trueConstant numbers β
const PI = 3.14Objects β
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 kinds of variables. They are variables that 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
you can find more in depth information about arrays in this page
Javascript Array in depthOperators
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 that 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 of 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 byencodeURIor 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 a loop executesdo whileβ Similar to thewhileloop 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 to 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 to 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 is 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 a 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 asscreenLeftbut needed for some browsersscreenYβ Same asscreenTopbut 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 the 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 a 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
Last updated
Was this helpful?