JavaScript Cheat Sheet

Today, We are going to discuss JavaScript Cheat Sheet.

Javascript is an event-based or client-side scripting language with the ability of object-oriented programming concepts, Brendan Eich invented Javascript in 1995.

Javascript is mainly used in making dynamic web pages and it can be used in game development as well. Javascript can be used with HTML and CSS.

So let’s start JavaScript Cheat Sheet with the basics of JavaScript.

Basics Of JavaScript

Let’s see how to include Javascript in your HTML file internally and externally.

If you are working on an HTML file and want to add JS within your file so you just have to simply write the following piece of code.

Syntax

<script type="text/javascript">
//JS code goes here
</script>

Note: You can add the above piece of code at the end of your HTML file.

If you don’t want a messy code and want to see your code manageable so you can create a separate file for JS code. You can call that file externally by following the syntax below.

Syntax

<script src="yourfilename.js"></script> 

By following the above code you can add your external JS file inside the HTML file easily.

Note: while creating the external JS file don’t forget to add “.js” extension with your file name.

Variables In JavaScript

Variables are used to store temporary data to perform different operations.

A variable can store a limited value of different data types.

Types of variables in JS

There are three ways of declaring a variable.

  1. var
  2. const
  3. let

Var

It is the most commonly used type of variable it can be reassigned and can only be used inside only in that function in which it is declared.  You can declare a var variable like below.

Example

var  a = 10;

var  a = “ this is a number”;

Const

This type of variable cannot be reassigned and cannot be accessible before appearing in the code. 

Example

const  abc = 10;

const  abc = “ this is a number”;

It will throw an error because it can’t be reassigned.

Let

This type of variable works like the const variable the difference is that we can reassign it.

Example

let  abc = 10;

let abc = “ this is a number”;

Data Types In JavaScript

As we are discussing JavaScript Cheat Sheet Data Types is the very main topic in it. The data which we store in a variable has a proper type, every value has its own data type, and it checks which type of data is stored in the variable.  

Different values contain different data types, few are explained below.

Numbersvar num = 98
Variablesvar i
Text (strings)var a = “init”
Operationsvar b = 1 + 2 + 3
True or false statementsvar c = true
Constant numbersconst PI = 3.14
Objectsvar name = {firstName:”peter”, lastName:”parker”}

Arrays In JavaScript

Arrays are used to store permanent data, we can store multiple values in Arrays.

Example

var arr = ["Accord", "Civic", "Corolla"];

Types of Arrays in JS

There are three types of Arrays.

  1. One Dimensional Array
  2. Multidimensional Array
  3. Associative Array

One Dimensional Array

In a one-dimensional array, multiple values are stored in a single array.

Example

var arr = ["Accord", "Civic", "Corolla"];

Multidimensional Array

In a multidimensional array, we can store multiple arrays with multiple values.

Example

Var  arr = array(
  array= ["Audi", "Civic", "Corolla"],
  array= ["Audi", "Civic", "Corolla"],
  array= ["Audi", "Civic", "Corolla"]
);

Associative Array

In an associative array, we assign a key to each value.

Example

var array = [ “1”=>"Accord", “2”=>"Civic", ”3”=> "Corolla"];

Array Methods In JavaScript

After declaring Arrays we can perform several tasks by using Array Methods, a few of them are explained below with examples.

concat()This method combines multiple arrays into a single array.let demo1 = “java”;let demo2 = “script”;let result = demo1.concat(demo2);document.write(result);

indexOf()
This method starts searching your desired element from the start of an array then returns the index number of your desired element.let arr = [“Hello” ,”dear” ,”world”];let result = arr.indexOf(“world”);document.write(result);
join()This method Combine elements of an array into a single string and returns the string.const cars = [“Audi”, “Corolla”, “Civic”, “Mehran”];let result = cars.join();document.write(result);
lastIndexOf()This method starts searching your desired element from the end of an array then returns the index number of your desired element.let arr = [“Hello” ,”dear” ,”world”];let result = arr.lastIndexOf(“world”);document.write(result);
pop()This method used to remove the last element of an array<p id=”example”></p><script>const cars = [“Audi”, “Corolla”, “Civic”, “Mehran”];cars.pop();document.getElementById(“example”).innerHTML = cars;
push()This method is used to Add a new element at the end of an array.<p id=”example”></p><script>const cars = [“Audi”, “Corolla”, “Civic”, “Mehran”];cars.push(“Mercedes”);document.getElementById(“example”).innerHTML = cars;
reverse()This method is used to Sort the elements of an array in a descending order.<p id=”example”></p><script>const cars = [“Audi”, “Corolla”, “Civic”, “Mehran”];document.getElementById(“example”).innerHTML = cars.reverse()
shift()this method is used to Remove the first element from the array<p id=”example”></p><script>const cars = [“Audi”, “Corolla”, “Civic”, “Mehran”];cars.shift();document.getElementById(“demo”).innerHTML = cars;</script>
slice()This method used to pull a copy of your chosen elements of an array into a new array.const cars = [“Audi”, “Corolla”, “Civic”, “Mehran”];const car = cars.slice(1, 3);document.write(car)
sort() This method is used to Sort elements alphabetically or sequentially.const cars = [“Audi”, “BMW”,”Corolla”, “Farari”];const cr = cars.sort();document.write(cr);
splice() This method is used to Add elements in an array by passing  a specified position and element.<p id=”example”></p><script>const cars = [“Audi”,”Corolla”, “Farari”,”BMW”];// At position 2, add 2 elements:cars.splice(2, 0, “Mehran”, “Alto”);document.getElementById(“example”).innerHTML = cars;</script>
toString() This method is done used to Convert elements to strings.let cars = [“Audi”,”Corolla”, “Farari”,”BMW”];let demo = cars.toString();document.write(demo);
unshift()This method is used to Add a new element at the starting of an array.<p id=”example”></p><script>let cars = [“Audi”,”Corolla”, “Farari”,”BMW”];cars.unshift(“Mercedes”, “Civic”);document.getElementById(“example”).innerHTML = cars;</script>
valueOf() This method is used to Return the primitive value of itself.<p id=”example”></p><script>let a = “JavaScript js!”;let result = a.valueOf();document.getElementById(“example”).innerHTML = result;</script>

Operators In Javascript

With Javascript variables we can perform several tasks, to perform that we will need some operators.

Types of Operators

There are four types of operators in Javascript.

  1. Arithmetic
  2. Comparison
  3. Logical
  4. Bitwise

Arithmetic or Basic Operators

Arithmetic operators are used to performing basic mathematical operations.

+Addition12+2
Subtraction21-2
*Multiplication12*2
/Division12/2
(…)Grouping operator(value1 + “</br>” + value2);
%Modulus (remainder )10%2
++Increment numbers(2++)
Decrement numbers(2–)

Comparison Operators

These types of operators are used to compare a value with another value.

==Equal toValue1==value2
===Equal value and equal typeValue1===value2
!=Not equalValue1 != value2
!==Not equal value or not equal typeValue1 !== value2
>Greater thanValue1> value2
<Less thanValue 2<value1
>=Greater than or equal toValue1>=value2
<=Less than or equal toValue2<=value1
?Ternary/conditional operator Value1?value2

Logical Operators

Logical operators are used to performing logical tasks.

&&Logical andValue1>value2 && value2<value3
||Logical orValue1>value2 || value2<value3
!Logical notValue1>=value2 ! value2>=value3

Bitwise Operators

&AND statementValue1&value2
|OR statementValue1|value2
~NOTValue1~ value2
^XORValue1^value2
<<Left shiftValue<<value2
>>Right shiftValue2>>value1
>>>Zero fill right shiftValue1>>>value2

Functions In JavaScript

In Javascript , a function is used to perform a particular task. We can make our own function to perform a task, the syntax of creating a function is below.

Syntax

function name(parameter1, parameter2, parameter3) {	
}
i.e  function add(a, b){
//( you can create a function like this)
} 

Outputting Data In Javascript

There are various ways to output the data of your function, a few of them are explained below.

alert()The alert() method is used to show data in an alert box on your browser.
confirm()The confirm() method is used to show a confirmation message on a user click.
console.log()The console.log() method is used to Write information in the browser’s console area.
document.write()The document.write() method is used to Write in the HTML file.
prompt()The prompt() method takes user input through a dialogue box. Or show the true-false value on user click.

Global Functions In Javascript

Global functions are those functions that make browsers able to run Javascript.It’s also a main part of Javascript Cheat Sheet.

encodeURI()This function is used to Encode a URI into UTF-8.var enc = “hackr.io/ecommerce”;var uri = encodeURI(enc);
encodeURIComponent()This method is used for Encoding URI components.var enc = “hackr.io/ecommerce”;var ur = encodeURIComponent(enc);
decodeURI()This function is used to Decode a “Uniform Resource Identifier (URI)” which is made by  encodeURI.var dcd = decodeURI(enc);
decodeURIComponent()This function is used to Decode a URI componentvar dcp = decodeURIComponent(enccomp);
parseInt()This function Parses the input value and returns an integer.var pri = parseInt(“1998 friday”);
parseFloat()This function is used to Parse the input value and to return a floating-point number.var prf = parseFloat(“28.443”);
eval()This function is used to Evaluate JavaScript code which is represented as a string.var i = eval(“4 * 4”);
Number()This method is used to Return a number which is converted from its initial value.var x = new Date();var y = Number(x);
isNaN()This function is used to  Determine if the value is NaN or notisNan(35);
isFinite()This function is used to Determine whether the passed value is a finite number or not.isFinite(-356);

Loops In Javascript

Loops are used when we want to print a condition continuously or when we want repetition in our code. The basic syntax of writing loop conditions as defined below.

There are three types of loops in Javascript.

  1. For
  2. While
  3. Do while

For Loop

It is the most commonly used type of loop For loop is used when we want to repeat the data with a limit in our document. It’s a finite loop.

Syntax

for(init; condition; increment/decrement)
{  // code goes here 
}

Example

var j;
for (j = 0; j < 5; j++) {
  document.write(j);
}

While Loop

It is also the most commonly used type of loop. while loop is used when we want to apply the condition and it starts printing data when the condition is true. We can call it an infinite loop because it never stops and keeps repeating the data when the condition is true.

Syntax

while (condition){    
//code goes here   
Increment / decrement statement  
}

Example

while (age > 25){  
document.write(age);
}

Do While Loop

Do while is similar to a while loop the only difference is, that it executes first before checking the condition.

Syntax

do{    
//code does here
//update statement   
}while (condition);   

Example

do {
i++;
document.write(i);
} while (i<5){
}

Break

The break is used in the middle of code execution when we need to stop the loop.

Continue

Continue is used when we want the code keeps executing. 

If-Else statement In JavaScript

Here we will discuss If-Else statements in Javascript Cheat Sheet.

The if-else statement is used when we want to check whether the condition is working or not.

If part of the statement executes when the condition matches, if it is not so, the Else part of the statement executes.

Syntax

if (condition) {
    // what to do if condition is matched
} else {
    // what to do if condition isn’t matched
}

Example

if (age>20) {
    document.write(“you are an adult”);
} else {
    Document.write(“you are a teenager”);
}

Strings In JavaScript

Javascript Strings are used to store multiple characters. Mean to say you can assign more than one character or a sentence in a string.

Example

let str=”Peter Parker”; 
Let txt=” he is, ‘peter’ ”;

String Methods

MethodUsageExample
Length()The length method uses to determine the length of the string.
let txt = “Hello dear World!”;let lng = txt.length;
indexof()The indexof() method use to find position of the first happening of character in a string.let txt = “He is a nice man.”;let res = txt.indexOf(“is”);
lastindexof()The lastindexof() method is use to return last happening of character in a string.let txt = “He is a nice man.”;let res = txt.lastIndexOf(“nice”);
search()The search() method is used to search in string and return the position of a searched value.let txt = “he has a red Tshirt”let pos = txt.search(“red”);
slice()The slice() method is used to return a part of  string as a new string.let txt = “Hello dear world!”;let res = txt.slice(0, 8);
Substring()The substring() method is used to return a  part of the string from the start of the index and to the end of the index. It did not take a negative value.let txt = “Hello People!”;let res = txt.substring(0, 8);
substr()The substr() method is used to return the cut-out part of string, the second parameter will be the length of the final string.let txt = “Hello People!”;let res = txt.substr(1, 4);
replace()The replace() method is used to replace a specified value with another value.let txt = “like the page!”;let res = txt.replace(“page”, “Website”);
touppercase()The touppercase method is used to convert  all aplhabets into uppercase.let txt = “Hello People!”;let res = txt.toUpperCase();
tolowercase()The tolowercase method is used to convert  all aplhabets into tolowercase.let txt = “HELLO PEOPLE!”;let res = txt.tolowerCase();
concat()The concat() method is used to combine two or more than two strings together into new string.let txt1 = “ecommerce”;let txt2 = “website”;let res = txt1.concat(txt2);
trim()The trim method is used to cut the white spaces in a string.let txt = ”       Hello People!        “;let res = txt.trim();
charat()The charart() method is used to find a  character at a particular position.let txt = “HELLO PEOPLE”;let res = txt.charAt(1);
charcodeat()The charcodeat() method is used to return the unicode of character at the particular position.let txt = “HELLO UNIVERSE”;let res = txt.charCodeAt(0);
split()The split() method is used to change a string into an array-based special character.let txt = “How was your day?”;const res = text.split(” “);

Escape Characters

\’ Single quote
\” Double quote
\\Backslash
\b Backspace
\fForm feed
\nNew line
\rCarriage return
\t Horizontal tabulator
\v Vertical tabulator

Number Properties In JavaScript

  • MAX_VALUE:

 It shows the maximum numeric value in JavaScript.

  • MIN_VALUE 

 It shows the minimum numeric value in JavaScript.

  • NaN 

NaN stands for “Not-a-Number” value.

  • NEGATIVE_INFINITY

It shows the negative Infinite value in Javascript.

  • POSITIVE_INFINITY

It shows the Positive Infinite value in Javascript.

Number Methods in JavaScript

  • toExponential()

this method returns a string with a rounded number that is written as exponential form.

  • toFixed() 

this method returns the string of a number with defined decimal numbers.

  • toPrecision()

this method returns a string of a number written with a defined length.

  • toString()

this method returns a number as a string.

  • valueOf()

this method returns a number as a number.

Math Properties In JavaScript

E E is the Euler’s number
LN2 LN2 is the natural logarithm of 2
LN10 LN10 is the Natural logarithm of 10
LOG2E LOG2E is the Base 2 logarithm of E
LOG10E LOG10E is the Base 10 logarithm of E
PI PI is the number of PI which is(3.14)
SQRT1_2 SQRT1_2 is the Square root of 1/2
SQRT2 SQRT2 is the square root of 2

Math Methods In JavaScript

  • abs(x)

The abs(x) method is used to return the fixed (positive) value of x.

  • acos(x) 

 The acos(X) method shows the arccosine of x, in radians.

  • asin(x)

the asin(x) method shows the Arcsine of x, in radians.

  • atan(x) 

the atan(x) method gives the arctangent of x as a numeric value.

  • atan2(y,x) 

the atan2(y,x) method gives the Arctangent of the quotient of its arguments.

  • ceil(x) 

the ceil(x) method shows the value of x rounded up to its nearest integer

  • cos(x)

The cos(x) method shows the cosine of x (x is in radians).

  • exp(x) 

the exp(x) method shows the Value of Ex

  • floor(x) 

the floor method shows the value of x rounded down to its closest integer.

  • log(x) 

The log(x) method shows natural logarithm (base E) of x

  • max(x,y,z,…,n) 

this method returns the number with the maximum value.

  • min(x,y,z,…,n) 

this method returns the number with the minimum value.

  • pow(x,y) 

this method returns X to the power of y.

  • random() 

this method returns a random number between 0 and 1.

  • round(x) 

this method returns the value of x rounded to its closest integer.

  • sin(x) 

The sin(x) method shows the sine value of x (x is in radians).

  • sqrt(x) 

the sqrt(x) method gives the Square root of x.

  • tan(x) 

The tan(x) method gives the tangent of an angle.

Get Date And Time Methods In JavaScript

Date()

Date() method Creates a new date object with the ongoing date and time.

Date(2017, 5, 21, 3, 23, 10, 0) 

Creates a custom date object. Format – (yyyy, mm, dd, hh, min, s, ms). You can skip dd, hh, min, s, and ms but cant skip year and month because it is not optional.

Date(“2017-06-23”)

It declares a Date as a string.

getDate() 

 by using this method you can Get the day of the month as a number (1-31).

getDay()

 by using this method you can Get the weekday as a number (0-6)

getFullYear()

it gives a Year as a four-digit number (yyyy).

getHours()

 by using this method you will Get the hours (0-23).

getMilliseconds() 

by using this method you will get milliseconds (0-999).

getMinutes() 

 by using this method you will Get the minutes (0-59).

getMonth() 

 by using this method you will get the Month as a number (0-11)

getSeconds() 

 by using this method you will Get the seconds (0-59)

getTime() 

 by using this method you will Get the milliseconds since January 1, 1970

getUTCDate() 

 The day (date) of the month in the defined 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 Date And Time Methods In JavaScript

setDate() The setDate() Sets the day as a number (1-31).
setFullYear()  The setFullYear() Sets the year (month and day are optional).
setHours()the setHour() Sets the hour (0-23).
setMilliseconds()  The setMilliseconds() Sets milliseconds (0-999).
setMinutes()  The setMinutes() Sets the minutes (0-59).
setMonth()  The setMonth() Sets the month (0-11).
setSeconds()  The setSeconds() Sets the seconds (0-59).
setTime()  The setTime() Sets the time (milliseconds since January 1, 1970).
setUTCDate()  The setUTCDate() Sets the day of the month for a defined date according to universal time.

DOM 

DOM stands for Document Object Model. DOM is the code of the page layout. HTML elements known as nodes can be handled easily by using JavaScript.

Node Properties

  • attributes 

The attributes propertyReturns a list of all attributes if it is an HTML element.

  • baseURI 

The baseURI Provides the fixed base URL of an HTML element.

  • childNodes

The childNodes property Gives a list of all HTML element’s child nodes.

  • firstChild 

The firstChild property Returns the first child node of an HTML element.

  • lastChild 

 The lastChild property returns the last child node of an HTML element.

  • nextSibling 

The nextSibling property Gives you the next node as soon as the node tree level.

  • nodeName 

The nodeName property Returns the name of a node.

  • nodeType 

The nodeType property Returns the type of a node.

  • nodeValue 

The nodeValue property Sets the value of a node.

  • ownerDocument

The ownerDocument property returns a top-level or root document object for a node.

  • parentNode 

The parentNode property Returns the parent node of an HTML element.

  • previousSibling 

The previousSibling property Returns the node immediately before the present node.

  • textContent 

The textContent property returns the textual content of a node and its descendants.

Node Methods

  • appendChild()

The appendChild()  Adds a new child node to an HTML element as the last child node.

  • cloneNode() 

The cloneNode() Clones an HTML element.

  • compareDocumentPosition() 

The compareDocumentPosition() Compares the document position of two HTML elements.

  • getFeature() 

The getFeature() is used to get the feature of an element and it Returns an object which implements the APIs of a defining feature.

  • hasAttributes() 

The hasAttributes() Returns true if an element has any attributes, otherwise, it returns false.

  • hasChildNodes() 

The hasChildNodes() Returns true if an element has any child node, otherwise, it returns false.

  • insertBefore() 

The insertBefore() Inserts a new child node before a defined or existing child node.

  • isDefaultNamespace() 

The is DefaultNamespace() Returns true if a specified namespaceURI is the default, otherwise false.

  • isEqualNode() 

The isEqualNode Checks if two elements are equal.

  • isSameNode() 

The isSameNode() Checks if two elements are the same node.

  • isSupported() 

The isSupported() Returns true if a defining feature is supported on the element.

  • lookupNamespaceURI()

The lookupNamespaceURI() Returns the namespace URI associated with a given node.

  • lookupPrefix() 

The lookupPrefix() Returns a DOMString having the prefix for a mentioned namespace URI if present.

  • normalize()

It is used to Join adjacent text nodes and deletes empty text nodes in an HTML element.

  • removeChild() 

It is used to Remove a child node from an HTML element.

  • replaceChild() 

It is used to Replace a child node in an HTML element.

Element Methods

getAttribute()This method is used to find an Html attribute element by mentioning its attribute name and then we can access the attribute.
getAttributeNS() This method Returns string value of the attribute with the defined namespace and name.
getAttributeNode() This method Gets the specified attribute node.
getAttributeNodeNS()this method Returns the attribute node for the attribute with the mentioned namespace and name.
getElementsByTagName()this method is used to get a HTML Tag element by mentioning its tag name.
getElementsByTagNameNS() This method returns a live HTMLCollection of elements with a certain tag name belonging to the mentioned namespace.
hasAttribute() This method returns true if an element has an attribute, otherwise returns false.
hasAttributeNS() This method Provides a Boolean value, true/false value which indicates whether the current element in a given namespace has the defined attribute or not.
removeAttribute()This method Removes a defined attribute from an element. 
removeAttributeNS()This method deletes the defined attribute from an element within a precise namespace. 
removeAttributeNode() This method Takes away a defined attribute node and returns the deleted node.
setAttribute() This method Sets or converts the defined attribute to a specified value.
setAttributeNS() This method Adds a new attribute or converts the value of an attribute into the given namespace and name.
setAttributeNode() This method Sets or converts the defined attribute node.
setAttributeNodeNS()this method Adds a new namespaced attribute node to an element.

Window Properties

closedthe closed window property Checks whether a window has been closed or not and returns true or false.
defaultStatus The defaultstatus property Sets the default text in the status bar of a window.
documentThe document window property sets the document object for the window.
frames The frames window property returns a list of all window objects.
history The history window property Provides the History object for the window.
innerHeight This window property returns the inner height of a window’s content area.
innerWidth This property returns The inner width of the content area.
length The length window property returns the number of windows in the window.
location The location window property does have the location information related present URL.
nameThe name window property Sets or returns the name of a window.
navigator The navigator window property Returns the Navigator object for the window.
opener The opener window property Returns a reference to that window that generates the window.
outerHeight The outer height of a property, including toolbars/scrollbars
outerWidth The outerWidth window property gives the outer width of a window.
pageXOffset ThepageXOffset window property gives the number of pixels the present file has scrolled horizontally.
pageYOffset ThepageYOffset window property gives the number of pixels the present file has scrolled vertically.
parent The parent window property returns The parent window of the present window.
screen The screen window property has the information of the user’s screen.
screenLeftThe screenLeft window property returns the x and y coordinate of the window.
screenTopThe screenTop window property returns the x and y coordinates of the window.
screenX The screenX window property is the same as screen left it also provides horizontal coordinate.
screenY The screen window property provides a vertical coordinate Y which is relative to the screen.
SelfThe self window property Returns the present window.
statusThe status window property sets the text in the status bar of a window.
top The top window property returns the topmost window in the present browser.

Window Methods

alert()This method shows an alert box with a message written in it and an OK button.
blur()This method deletes focus from the present window.
clearInterval()This method Clears a timer set with setInterval().
clearTimeout() This method Clears a timer set with setTimeout().
close() This method Closes the present window.
focus() This method Sets focus to the present window.
moveBy() This method Moves a window relative to its present coordinate.
moveTo() This method Moves a window to a defined position.
open() This method opens another browser window.
print() This method prints the data of the present window.
prompt() This method shows a dialogue box that prompts a user for taking input.
resizeBy()This method resizes the window by the defined number of pixels.
resizeTo()This method resizes the window to a defined width and height.
scrollBy() This method Scrolls the file by a defined number of pixels.
scrollTo() This method Scrolls the file to defined coordinates.
setInterval() This method calls a function at a defined interval.
setTimeout()This method calls a function after a defined interval.
stop()This method stops the window to load.

Screen Properties

  • availHeight 

This property tells the height of the screen

  • availWidth

This property tells the width of the screen.

  • colorDepth

This property returns the color depth for images.

  • height 

This property returns the total height of the screen.

  • pixelDepth 

This property returns the color resolution of the screen in bits per pixel.

  • width 

This property tells the total width of the screen.

User Events

Mouse

OnclickThe onclick event occurs when a user clicks on an HTML element.
onmouseoverThe onmouseover event occurs when the mouse is moved over some HTML element.
onmouseoutThe onmouseout event occurs when the User moves the mouse pointer out of an HTML element or one of its children.
onmouseupThe onmouseup event occurs when a user releases a mouse button while over an HTML element.
onmousedownThe onmousedown event occurs when the user moves a mouse down over an HTML element.
onmouseenterThe onmousenter event occurs when a pointer moves onto an HTML element.
onmouseleaveThe onmouseleave event occurs when a Pointer moves out of an element.
onmousemoveThe onmousemove event occurs when a pointer is moving when it is over an element.
oncontextmenuThe oncontextmenu event occurs when the user right-clicks on an element to open a context menu.
ondblclickThe ondblclick event occurs when a user clicks twice on an element.

Keyboard

onkeydownThe event occurs when the user pressed a down key.
onkeypressAn event occurs when the user pressed any key.
OnkeyupThe moment when the user released a key.

 

Frame

onabort The onabort event occurs when the media loading is aborted.
onbeforeunload An Event occurs before unloading a file.
onunload An Event occurs when a page has unloaded.
onerror onerror event occurs while loading an external document.
onhashchange An event occurs when The anchor part of the URL changes.
onload An event occurs when an object is loaded.
onpagehide Occurs When a user crosses away from a webpage.
onpageshow Occurs when the user crosses the webpage.
.onresize Occurs when the file view is resized.
onscroll An event occurs when an element’s scrollbar is scrolling.

Form

onblurThe onblur event occurs When an element loses focus.
onchangeThe onchange event occurs when an element from the page changes.
onfocusThe onfocus event occurs when an element is focused.
onfocusinAn event occurs When an element is going to get focused.
onfocusoutAn event occurs when an element is going to lose focus.
oninputThis event occurs when a user gives input on an element.
oninvalidThis event occurs when an invalid element is found.
onresetThis event occurs when a form is reset.
onsearchThis event occurs when the user searches in the search bar element.
onselectThis event occurs when the user selects a text element. Like input textarea.
onsubmitThis event occurs when a user submits the form.

Drag

OndragThe ondrag event occurs when An element is dragged.
OndropThe ondrop event occurs when the dragged element is dropped.
OndragstartThe ondragstart event occurs when the user starts to drag an element.
OndragendThe ondragend event occurs when the user stopped dragging the element.
OndragenterThe ondragenter event occurs when the dragged element is entered.
OndragleaveThe ondragleave event occurs when a dragged element leaves.
OndragoverThe ondragover event occurs when The dragged element is over the drop target.

 

Clipboard

OncutWhen a user cuts the content of an element
Oncopywhen a user copies the content of an element
Onpastewhen a user pastes the content of an element

 

Media

OnabortAn event that occurs when Media loading is aborted.
OnendedAn event that occurs when the media is ended.
OnerrorAn event that occurs when an error generates while loading an external document.
OncanplayAn event that occurs when the browser is able to start playing media.
oncanplaythroughAn event that occurs when The browser is able to play through media without stopping the media.
ondurationchangeAn event that occurs when the change gets done in the duration of media.
OnloadeddataAn event occurs when the data of media is loaded.
onloadedmetadataAn event that occurs when the Metadata is loaded.
OnloadstartAn event that occurs when the browser starts searching for defined media.
OnpauseAn event that occurs when the Media is paused.
OnplayAn event that occurs when the media begin to play.
OnplayingAn event that occurs when a Media starts playing after being paused.
OnprogressAn event that occurs when the progress of the browser starts increasing while downloading any media.
onratechangeAn event occurs when the speed of playing media is changed.
OnseekedAn event that occurs when the user is stopped moving the position.
OnseekingAn event that occurs when the user starts skipping.
OnstalledAn event which occurs when the browser is trying to load the media but it is unavailable.
OnwaitingAn event that occurs when the media paused or buffered for some time.
OnsuspendAn event that occurs when the browser is intentionally not loading media.
ontimeupdateAn event that occurs when the playing position is changed.
onvolumechangeAn event that occurs when the Media volume has increased or reduced.

 

Others

 

TransitionendThis event occurs when a CSS transition is completed.
OnmessageThis event occurs when we got a message from the event source.
OnonlineThis event occurs when the browser starts working online.
OnofflineThis event occurs when the browser starts working offline.
OntoggleThis event occurs when The user opens or closes the <details> element.
OnpopstateThis event occurs when the window’s history is changed.
OnshowThis event occurs when a menu converts to the context menu after placing the cursor on it.
OnstorageThis event occurs when a Web Storage area is updated.
OnwheelThis event occurs when a mouse wheel moves up or down on an element.
OntouchstartThis event occurs when a finger is placed on the touch screen.
OntouchendThis event occurs when the User’s finger is removed from a touch-screen.
ontouchcancelThis event occurs when Screen-touch is interrupted.
OntouchmoveThis event occurs when the user’s finger is dragged over the screen.

Errors

Tryused when a block of code did not execute successfully.
Catchused when a block of code has to handle the error.
ThrowUsed when to specify a custom error message.
FinallyUsed when a block is always executed in any case of result.

 

Error-values

EvalErrorIt is an error that occurred in the eval() function.
RangeErrorWhen a number got out of range the Rang Error occurred.
ReferenceErrorWhen the illegal reference happens, the RefrenceError occurred.
SyntaxErrorWhen you make a mistake in the syntax then a SyntaxError occurred.
TypeErrorA TypeError generates when a function can’t be perform.
URIErrorAn encodeURI() error occurred when handling a function was used in an inappropriate way.

Regular Expressions

Pattern Modifiers

It accesses replacement.

It performs case-insensitive matching.

It performs global matching.

  • m

It performs multiple line matching.

It treats strings as a single line.

It allows comments and whitespace in the pattern.

It is an Ungreedy pattern.

Brackets

  • [abc]  

Use to find characters in the brackets.

  • [^abc] 

It is used to find characters without brackets.

  • [0-9] 

It is Used to find any digit from 0 to 9.

  • [A-z] 

Use to find any character from uppercase A to lowercase z.

  • (a|b|c) 

Used to find an alternative separated with |.

Metacharacters

Use to find a single character.

  • \w

It is a Word character.

  • \W 

It is a Non-word character.

  • \d 

It is a digit.

  • \D 

It is a non-digit character.

  • \s 

It is a Whitespace character.

  • \S 

It is a Non-whitespace character.

  • \b 

Use to find a match at the start or at the end of a word.

  • \B 

It is a match not at the start or not at the end of a word.

  • \0 

It is a NUL character.

  • \n 

It is a new line character.

  • \f 

It is a Form feed character.

  • \r 

It is a Carriage return character.

  • \t 

 Tab character

  • \v 

It is a vertical tab character.

  • \xxx 

It is a character defined by an octal number xxx.

  • \xdd 

A Character defined by a hexadecimal number dd.

  • \uxxxx 

It is a Unicode character defined by a hexadecimal number XXXX.

Conclusion

In this tutorial, we have covered JavaScript Cheat Sheet with all those important topics of Javascript which will help you in learning Javascript quickly.

Leave a Comment