JavaScript Cheat Sheet

By | October 22, 2019

JavaScript is the most powerful tool of the front-end development, and with continuous updates & frameworks JavaScript can also be used as the back-end tool. Here in this article, we have provided a cheat sheet for all the basic JavaScript. We have also provided the code snippet which you can directly copy if somewhere you get confused with the syntax.

Basic JavaScript Cheatsheet

We can include JavaScript in our HTML file in two ways.

Internal Including of Java Script

In this, we write the JavaScript code in the HTML pages itself inside the <script> tag

<script type="text/javascript">
// Code here     

External Including of JavaScript

In this method, we create a JavaScript document with an extension of .js and include it to our HTML page.

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

Comments in JavaScript

Comments are used to provide additional information about the code.

In JS we use // to comment out a single line and /* to comment out multiple lines


Single line comments - // single line comment
Multi-line comments - /* Multi line comment*/

Java Script Variable

In JS we have 3 keywords that we can use to declare a variable.

Variable Description Code Snippet
var var keyword is used to assign a variable. As JavaScript is a dynamic language so we do not need to specify the specific data type. var num_1 = 10;
const const is a keyword which is used to assign a variable, once we assign a variable with const we cannot modify its value const num_2 = 20;
let It is similar to const, but a let variable can be reassigned but not re-declared let num_2 = 30;

 Data Types in JavaScript

Data type Code Snippet
Number var x = 100;
String var x = “100”
Boolean var x =true;
null var x = null;
var x = { name:  "Sam",
age:  "29"

Array in JavaScript

var arr = [1,2,3,4,5,6]

Array Methods

Methods Description
concat() Join arrays to make one single array
indexOf() To get the index of a value
join() Combine all elements of an Array to make it a string
lastIndexOf() Give the last position of the array
pop() Remove the last element of the array
push() Add new element at the end of an array
reverse() Revere the array element
shift() Remove the first element of the array
slice() Create a new sequence of an array from the existing one
sort() Sort the elements of the array
splice() Add elements in a specified way and position
toString() Convent elements to the string
unshift() Add an element at the beginning of an array
valueOf() Return the position of the element

Operators in JavaScript

In JS we have many types of Operators, such as Arithmetic, conditional, logical and Bitwise operator operators.

Operators are the special symbol, we use to perform a specific task, and the operators always need operands to work.

Arithmetic Operators

 Operators Operator Name Code snippet
+ Addition 1 + 2 //3
Subtraction 2 – 1 //1
* Multiplication 2*2   //2
/ Division 4/2  //2
% Modules or remainder 10%2  //0
++ Increment
x++  //3
3-- //2

Comparison: It returns true or false value

Operators Operator Name
== Equal to
=== Equal value and data type
!= Not equal
!== Not equal value and data type
> Greater than
< less than
>= Greater than and equal to
<= less than and equal to
? Ternary Operator

Logical Operator: It operates on Boolean value:

Operators Operator Name
&& and
|| or
! Not

Bitwise Operator:

Operators Operator Name
& AND statement
| OR statement
~ Not
<< Left shift
>> Right Shift
>>> Zero fill right shift


Functions are used to perform a specific task.

User-defined functions in JavaScript:

function function_name (parameters)
//function task

Show Output on Screen

In JS we have some inbuilt functions which are used to show output or print something on the screen. 

Output Function Description Code Snippet
alert() An alert box show a box alert(“Hello world”)
confirm() It is similar to alert but it returns value in the form of true or false confirm(“Are you 18+”)
console.log() It is used to write information on the browser console console.log(“Hello world”)
document.write() It can write in HTML document document.write(“Hello world”)
prompt() It is used to take data from the user prompt(“Enter Your name”)

 JavaScript Global Functions

Global Functions Description
decodeURI() Decode a Uniform Resource iIdentifiers(URI)
decodeURIComponent() Decode a URI component
endodeURI() Encode a URI into UTF-8
encodeURIComponent() Encode URI components
eval() Evaluate the code represent in the string format
isFinite() Evaluate whether the value is finite or not
isNaN() Evaluate whether the value is NaN or Not
Number() Convert the string into a number
parseFloat() Parse the value and return into a floating-point number
parseInt() Parse the value and return an Integer

Loops in JavaScript

Loop is used to iterate over a block of Statement again and again till a certain condition.

In JS we have 3 types of statements that can loop over a statement.

Loop Description Code Snippet
for We use for a loop when we are certain about how many times we are going to iterate over a block of code. for( var i=0; i<10; i++)




while When we are not certain about how many times, we need to iterate over a block while(i<10)





do while No matter what, even the condition is false at first place to do while will execute a minimum 1 time. do





break: Break is a keyword we use in loop to stop and exit the cycle of the loop.

continue: Continue is used to skip a cycle of the loop.

JavaScript If…Else:

 if (condtion)
    //code if the statement is true
    //if the condition is false.


A string is a collection of characters inside the double or single inverted commas.

var string = "This is a string"
Escape Characters = \

String Methods

Methods Description
charAt() Return the position of the character inside a string.
charCodeAt() Provide the Unicode of the character
Concat() Join two or more strings into one
fromCharCode() Return a string created from the specified sequence of UTF-16 code units
indexOf() Returns the position of the character
lastIndexOf() Provide the last index of the character if there is more than one same character in the string.
match() Retrieves the matches of a string against a search pattern.
replace() Replace a text with another
search() Return the position of a text in a string
slice() Extract a sequence of string
split() Split the string into an array
substr() Extract a sequence of string depend on a specified number of characters
substring() Similar to slice() but does not work with -ve indices
toLoweCase() Covert the string to lowercase
toUpperCase() Convert the string to upper case
valueOf() Return the primitive value of a String object.

Regular Expression

Pattern Modifier Name
e Evaluate Replacement
i Case-insensitive matching
g Global matching
m Multiple line matching
s Treat string as a single line
x Allow comments and whitespace in pattern
u Ungreedy pattern


Brackets Description
[abc] Find any characters from a, b and c
[^abc] Find any character except abc
[0-9] Find any digit 0 to 9
[A-z] Find any character from a to z and A to Z
(a | b | c) Find any of the alternatives separated with |

Math and Numbers

NaN = Not A Number
Number Methods Description
toExponential() Return a string with a rounded number written as exponential notation
toFixed() Returns the string of a number with a specified number of decimals
toPrecision() A string of a number written with a specified length
toString() Returns a number as a string


Math Methods Description
abs(n) Return a positive value of n
acos(n) Arccosine of n in radian
asin(n) Arcsine of n in radians
atan(n) The arctangent of n in numeric value
ceil(n) The rounded-up value of n
cos(n) Cosine of n
exp(n) Ex of n
floor(n) Rounded down value of n
log(n) The natural logarithm of n
max(1,2,3,5,12,42) Return the maximum value
min(1,2,3,5,12,42) Return the minimum value
pow(n,m) n to the power m
random() Return a random value between 1 or 0
sin(n) The sine of x in radian
sqrt(n) The square root of n
tan(n) The tangent of angle n

Dates in JS

Date()= Return the current date in the form of a new date object.

Date Declaration

Date(yyyy,mm,dd,HH,MM,SS,MS): to create a new date object.

yyyy = year
mm = month
dd = day
HH = Hours
MM = Minutes
SS = seconds
MS = Milliseconds
Date("2019-11-29") = Date declaration as a string
Date("June 23 2019");
Date("Jun 23 2019 07:45:00 GMT+0100 (Tokyo Time)");

Date Methods

Get Date Methods Description
getDate() Get the date from the date object
getDay() Get the weeday
getFullYear() Get the year
getHours() Get the hour(0-23)
getMilliseconds() Get the millisecond
getMinutes() Get the minutes
getSeconds() Get the second
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, fullyear, hours, minutes etc.)
getMonth() Get the month(0-11)


Set Date Methods Description
setDate() Set the date
setFullYear() Set the year
setHours Set hours
setMilliseconds Set milliseconds
setMinutes Set minutes
setMonths() Set months
setSeconds() Set seconds
setTime() Set time
setUTCDate() Sets the day of the month for a specified date according to universal time (also available for day, month, fullyear, hours, minutes etc.)

 DOM in JavaScript

Node Methods Description
appendChid() Adds a new child node to an element as the last child node
cloneNode() Clone the HTML element
compareDocumentPosition() Compare the document position of two elements
getFeature() Returns an object which implements the API of a specified feature
hasAttributes() True if element has attributes else it return false
hasChildNode() Returns true if an element has any child nodes, otherwise fals
insertBefore() Insert a new child node before a specified existing child node
isDefaultNamespace() True for default specified namespaceURI else false
removeChild() Removes a child node from an element
replaceChild() Replaces a child node in an element


Elements Methods Description
getAttribute() Return the attribute value
getAttributeNS() Return the string value of the attribute with namespace
getAttributeNode() Get the specific attribute node
getAttributeNodeNS() Return the attribute node for the attribute with the given namespace
getElementsByTagName() Get all the elements with a specific tag name
getElemetsByTagNameNS() Returns a live HTMLCollection of elements with a certain tag name belonging to the given namespace
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

JavaScript Events

  • onclick
  • oncontextmenu
  • ondblclick
  • onmousedown
  • onmouseenter
  • onmouseeleave
  • onmousemove
  • onmouseover


  • onkeydown
  • onkeypress
  • onkeyup


  • onblur
  • onchange
  • onfocus
  • onfocusin
  • onfocusout
  • oninput
  • oninvalid
  • onrest
  • onsearch
  • onselect
  • onsubmit


  • ondrag
  • ondragend
  • ondragenter
  • ondragleave
  • ondragover
  • ondragstart
  • ondrop


  • onabort,
  • oncanplay,
  • oncanplaythrough,
  • ondurationchange,
  • onended,
  • onerror,
  • onloadeddata,
  • onloadedmetadata,
  • onloadstart,
  • onpause,
  • onplay,
  • onplaying,
  • onprogress,
  • onratechange,
  • onseeked,
  • onseeking,
  • onstalled,
  • onsuspend,
  • ontimeupdate,
  • onvolumechange,
  • onwaiting

You may also Interested In:

Leave a Reply

Your email address will not be published. Required fields are marked *