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 with var 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 to const, the let 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 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 one

  • indexOf() β€” Returns the first position at which a given element appears in an array

  • join() β€” Combine elements of an array into a single string and return the string

  • lastIndexOf() β€” Gives the last position at which a given element appears in an array

  • pop() β€” Removes the last element of an array

  • push() β€” Add a new element at the end

  • reverse() β€” Sort elements in a descending order

  • shift() β€” Remove the first element of an array

  • slice() β€” Pulls a copy of a portion of an array into a new array

  • sort() β€” Sorts elements alphabetically

  • splice() β€” Adds elements in a specified way and position

  • toString() β€” Converts elements to strings

  • unshift() β€”Adds a new element to the beginning

  • valueOf() β€” Returns the primitive value of the specified object

you can find more in depth information about arrays in this page

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 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 window

  • confirm() β€” Opens up a yes/no dialog and returns true/false depending on user click

  • console.log() β€” Writes information to the browser console, good for debugging purposes

  • document.write() β€” Write directly to the HTML document

  • prompt() β€” 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 by encodeURI or similar

  • decodeURIComponent() β€” Decodes a URI component

  • encodeURI() β€” Encodes a URI into UTF-8

  • encodeURIComponent() β€” Same but for URI components

  • eval() β€” Evaluates JavaScript code represented as a string

  • isFinite() β€” Determines whether a passed value is a finite number

  • isNaN() β€” Determines whether a value is NaN or not

  • Number() β€”- Returns a number converted from its argument

  • parseFloat() β€” Parses an argument and returns a floating-point number

  • parseInt() β€” 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 JavaScript

  • while β€” Sets up conditions under which a loop executes

  • do while β€” Similar to the while loop but it executes at least once and performs a check at the end to see if the condition is met to execute again

  • break β€”Used to stop and exit the cycle at certain conditions

  • continue β€” 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 string

  • charCodeAt() β€” Gives you the Unicode of a character at that position

  • concat() β€” Concatenates (joins) two or more strings into one

  • fromCharCode() β€” Returns a string created from the specified sequence of UTF-16 code units

  • indexOf() β€” Provides the position of the first occurrence of a specified text within a string

  • lastIndexOf() β€” Same as indexOf() but with the last occurrence, searching backward

  • match() β€” Retrieves the matches of a string against a search pattern

  • replace() β€” Find and replace specified text in a string

  • search() β€” Executes a search for a matching text and returns its position

  • slice() β€” Extracts a section of a string and returns it as a new string

  • split() β€” Splits a string object into an array of strings at a specified position

  • substr() β€” Similar to slice() but extracts a substring depending on a specified number of characters

  • substring() β€” Also similar to slice() but can’t accept negative indices

  • toLowerCase() β€” Convert strings to lower case

  • toUpperCase() β€” Convert strings to upper case

  • valueOf() β€” 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 replacement

  • i β€” Perform case-insensitive matching

  • g β€” Perform global matching

  • m β€” Perform multiple line matching

  • s β€” Treat strings as a single line

  • x β€” Allow comments and whitespace in the pattern

  • U β€” 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 n

  • n* β€” Any string that contains zero or more occurrences of n

  • n? β€” A string that contains zero or one occurrence of n

  • n{X} β€” String that contains a sequence of X n’s

  • n{X,Y} β€” Strings that contain a sequence of X to Y n’s

  • n{X,} β€” Matches any string that contains a sequence of at least X n’s

  • n$ β€” 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 JavaScript

  • MIN_VALUE β€” Smallest positive numeric value representable in JavaScript

  • NaN β€” The β€œNot-a-Number” value

  • NEGATIVE_INFINITY β€” The negative Infinity value

  • POSITIVE_INFINITY β€” Positive Infinity value

Number Methods

  • toExponential() β€” Returns the string with a rounded number written as exponential notation

  • toFixed() β€” Returns the string of a number with a specified number of decimals

  • toPrecision() β€” String of a number written with a specified length

  • toString() β€” Returns a number as a string

  • valueOf() β€” Returns a number as a number

Math Properties

  • E β€” Euler’s number

  • LN2 β€” The natural logarithm of 2

  • LN10 β€” Natural logarithm of 10

  • LOG2E β€” Base 2 logarithm of E

  • LOG10E β€” Base 10 logarithm of E

  • PI β€” The number PI

  • SQRT1_2 β€” Square root of 1/2

  • SQRT2 β€” The square root of 2

Math Methods

  • abs(x) β€” Returns the absolute (positive) value of x

  • acos(x) β€” The arccosine of x, in radians

  • asin(x) β€” Arcsine of x, in radians

  • atan(x) β€” The arctangent of x as a numeric value

  • atan2(y,x) β€” Arctangent of the quotient of its arguments

  • ceil(x) β€” Value of x rounded up to its nearest integer

  • cos(x) β€” The cosine of x (x is in radians)

  • exp(x) β€” Value of Ex

  • floor(x) β€” The value of x rounded down to its nearest integer

  • log(x) β€” The natural logarithm (base E) of x

  • max(x,y,z,...,n) β€” Returns the number with the highest value

  • min(x,y,z,...,n) β€” Same for the number with the lowest value

  • pow(x,y) β€” X to the power of y

  • random() β€” Returns a random number between 0 and 1

  • round(x) β€” The value of x rounded to its nearest integer

  • sin(x) β€” The sine of x (x is in radians)

  • sqrt(x) β€” Square root of x

  • tan(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 time

  • Date(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, 1970

  • getUTCDate() β€” 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 element

  • baseURI β€” Provides the absolute base URL of an HTML element

  • childNodes β€” Gives a collection of an element’s child nodes

  • firstChild β€” Returns the first child node of an element

  • lastChild β€” The last child node of an element

  • nextSibling β€” Gives you the next node at the same node tree level

  • nodeName β€”Returns the name of a node

  • nodeType β€” Returns the type of a node

  • nodeValue β€” Sets or returns the value of a node

  • ownerDocument β€” The top-level document object for this node

  • parentNode β€” Returns the parent node of an element

  • previousSibling β€” Returns the node immediately preceding the current one

  • textContent β€” 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 node

  • cloneNode() β€” Clones an HTML element

  • compareDocumentPosition() β€” Compares the document position of two elements

  • getFeature() β€” Returns an object which implements the APIs of a specified feature

  • hasAttributes() β€” Returns true if an element has any attributes, otherwise false

  • hasChildNodes() β€” Returns true if an element has any child nodes, otherwise false

  • insertBefore() β€” Inserts a new child node before a specified, existing child node

  • isDefaultNamespace() β€” Returns true if a specified namespaceURI is the default, otherwise false

  • isEqualNode() β€” Checks if two elements are equal

  • isSameNode() β€” Checks if two elements are the same node

  • isSupported() β€” Returns true if a specified feature is supported on the element

  • lookupNamespaceURI() β€” Returns the namespace URI associated with a given node

  • lookupPrefix() β€” Returns a DOMString containing the prefix for a given namespace URI if present

  • normalize() β€” Joins adjacent text nodes and removes empty text nodes in an element

  • removeChild() β€” Removes a child node from an element

  • replaceChild() β€” Replaces a child node in an element

Element Methods

  • getAttribute() β€” Returns the specified attribute value of an element node

  • getAttributeNS() β€” Returns string value of the attribute with the specified namespace and name

  • getAttributeNode() β€” Gets the specified attribute node

  • getAttributeNodeNS() β€” Returns the attribute node for the attribute with the given namespace and name

  • getElementsByTagName() β€” Provides a collection of all child elements with the specified tag name

  • getElementsByTagNameNS() β€” Returns a live HTMLCollection of elements with a certain tag name belonging to the given namespace

  • hasAttribute() β€” Returns true if an element has any attributes, otherwise false

  • hasAttributeNS() β€” Provides a true/false value indicating whether the current element in a given namespace has the specified attribute

  • removeAttribute() β€” Removes a specified attribute from an element

  • removeAttributeNS() β€” Removes the specified attribute from an element within a certain namespace

  • removeAttributeNode() β€” Takes away a specified attribute node and returns the removed node

  • setAttribute() β€” Sets or changes the specified attribute to a specified value

  • setAttributeNS() β€” Adds a new attribute or changes the value of an attribute with the given namespace and name

  • setAttributeNode() β€” Sets or changes the specified attribute node

  • setAttributeNodeNS() β€” 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 false

  • defaultStatus β€” Sets or returns the default text in the status bar of a window

  • document β€” Returns the document object for the window

  • frames β€” Returns all <iframe> elements in the current window

  • history β€” Provides the History object for the window

  • innerHeight β€” The inner height of a window’s content area

  • innerWidth β€” The inner width of the content area

  • length β€” Find out the number of <iframe> elements in the window

  • location β€” Returns the location object for the window

  • name β€” Sets or returns the name of a window

  • navigator β€” Returns the Navigator object for the window

  • opener β€” Returns a reference to the window that created the window

  • outerHeight β€” The outer height of a window, including toolbars/scrollbars

  • outerWidth β€” The outer width of a window, including toolbars/scrollbars

  • pageXOffset β€” Number of pixels the current document has been scrolled horizontally

  • pageYOffset β€” Number of pixels the document has been scrolled vertically

  • parent β€” The parent window of the current window

  • screen β€” Returns the Screen object for the window

  • screenLeft β€” The horizontal coordinate of the window (relative to the screen)

  • screenTop β€” The vertical coordinate of the window

  • screenX β€” Same as screenLeft but needed for some browsers

  • screenY β€” Same as screenTop but needed for some browsers

  • self β€” Returns the current window

  • status β€” Sets or returns the text in the status bar of a window

  • top β€” Returns the topmost browser window

Window Methods

  • alert() β€” Displays an alert box with a message and an OK button

  • blur() β€” Removes focus from the current window

  • clearInterval() β€” Clears a timer set with setInterval()

  • clearTimeout() β€” Clears a timer set with setTimeout()

  • close() β€” Closes the current window

  • confirm() β€” Displays a dialogue box with a message and an OK and Cancel button

  • focus() β€” Sets focus to the current window

  • moveBy() β€” Moves a window relative to its current position

  • moveTo() β€” Moves a window to a specified position

  • open() β€” Opens a new browser window

  • print() β€” Prints the content of the current window

  • prompt() β€” Displays a dialogue box that prompts the visitor for input

  • resizeBy() β€” Resizes the window by the specified number of pixels

  • resizeTo() β€” Resizes the window to a specified width and height

  • scrollBy() β€” Scrolls the document by a specified number of pixels

  • scrollTo() β€” Scrolls the document to specified coordinates

  • setInterval() β€” Calls a function or evaluates an expression at specified intervals

  • setTimeout() β€” Calls a function or evaluates an expression after a specified interval

  • stop() β€” 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 images

  • height β€” The total height of the screen

  • pixelDepth β€” The color resolution of the screen in bits per pixel

  • width β€” 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 element

  • oncontextmenu β€” User right-clicks on an element to open a context menu

  • ondblclick β€” The user double-clicks on an element

  • onmousedown β€” User presses a mouse button over an element

  • onmouseenter β€” The pointer moves onto an element

  • onmouseleave β€” Pointer moves out of an element

  • onmousemove β€” The pointer is moving while it is over an element

  • onmouseover β€” When the pointer is moved onto an element or one of its children

  • onmouseout β€” User moves the mouse pointer out of an element or one of its children

  • onmouseup β€” The user releases a mouse button while over an element

Keyboard

  • onkeydown β€” When the user is pressing a key down

  • onkeypress β€” The moment the user starts pressing a key

  • onkeyup β€” The user releases a key

Frame

  • onabort β€” The loading of a media is aborted

  • onbeforeunload β€” Event occurs before the document is about to be unloaded

  • onerror β€” An error occurs while loading an external file

  • onhashchange β€” There have been changes to the anchor part of a URL

  • onload β€” When an object has loaded

  • onpagehide β€” The user navigates away from a webpage

  • onpageshow β€” When the user navigates to a webpage

  • onresize β€” The document view is resized

  • onscroll β€” An element’s scrollbar is being scrolled

  • onunload β€” Event occurs when a page has unloaded

Form

  • onblur β€” When an element loses focus

  • onchange β€” The content of a form element changes (for <input>, <select> and <textarea>)

  • onfocus β€” An element gets focus

  • onfocusin β€” When an element is about to get focus

  • onfocusout β€” The element is about to lose focus

  • oninput β€” User input on an element

  • oninvalid β€” An element is invalid

  • onreset β€” A form is reset

  • onsearch β€” 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 dragged

  • ondragend β€” The user has finished dragging the element

  • ondragenter β€” The dragged element enters a drop target

  • ondragleave β€” A dragged element leaves the drop target

  • ondragover β€” The dragged element is on top of the drop target

  • ondragstart β€” User starts to drag an element

  • ondrop β€” Dragged element is dropped on the drop target

Clipboard

  • oncopy β€” User copies the content of an element

  • oncut β€” The user cuts an element’s content

  • onpaste β€” A user pastes the content in an element

Media

  • onabort β€” Media loading is aborted

  • oncanplay β€” The browser can start playing media (e.g. a file has buffered enough)

  • oncanplaythrough β€” The browser can play through media without stopping

  • ondurationchange β€” The duration of the media changes

  • onended β€” The media has reached its end

  • onerror β€” Happens when an error occurs while loading an external file

  • onloadeddata β€” Media data is loaded

  • onloadedmetadata β€” Metadata (like dimensions and duration) are loaded

  • onloadstart β€” The browser starts looking for specified media

  • onpause β€” Media is paused either by the user or automatically

  • onplay β€” The media has been started or is no longer paused

  • onplaying β€” Media is playing after having been paused or stopped for buffering

  • onprogress β€” The browser is in the process of downloading the media

  • onratechange β€” The playing speed of the media changes

  • onseeked β€” User is finished moving/skipping to a new position in the media

  • onseeking β€” The user starts moving/skipping

  • onstalled β€” The browser is trying to load the media but it is not available

  • onsuspend β€” The browser is intentionally not loading media

  • ontimeupdate β€” 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 complete

  • animationiteration β€” CSS animation is repeated

  • animationstart β€” CSS animation has started

Other

  • transitionend β€” Fired when a CSS transition has completed

  • onmessage β€” A message is received through the event source

  • onoffline β€” The browser starts to work offline

  • ononline β€” The browser starts to work online

  • onpopstate β€” When the window’s history changes

  • onshow β€” A <menu> element is shown as a context menu

  • onstorage β€” A Web Storage area is updated

  • ontoggle β€” The user opens or closes the <details> element

  • onwheel β€” Mouse wheel rolls up or down over an element

  • ontouchcancel β€” Screen-touch is interrupted

  • ontouchend β€” User’s finger is removed from a touch-screen

  • ontouchmove β€” A finger is dragged across the screen

  • ontouchstart β€” 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 errors

  • catch β€” Set up a block of code to execute in case of an error

  • throw β€” Create custom error messages instead of the standard JavaScript errors

  • finally β€” 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 name

  • message β€” 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 the eval() function

  • RangeError β€” A number is β€œout of range”

  • ReferenceError β€” An illegal reference has occurred

  • SyntaxError β€” A syntax error has occurred

  • TypeError β€” A type error has occurred

  • URIError β€” An encodeURI() error has occurred

Last updated