JavaScript Cheatsheet
JavaScript Cheatsheet
CheatSheet
Follow @Raushan_Kuamr
JavaScript Basics
Set of JavaScript basic syntax to add, execute and write basic programming paradigms in
Javascript
On Page Script
External JS File
<script src="filename.js"></script>
Functions
function nameOfFunction () {
// function body
}
DOM Element
Output
console.log(a);
Conditional Statements
Conditional statements are used to perform operations based on some conditions.
If Statement
if (condition) {
// block of code to be executed if the condition is true
}
If-else Statement
If the condition for the if block is false, then the else block will be executed.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Else-if Statement
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is
} else {
// block of code to be executed if the condition1 is false and condition2 is
}
Switch Statement
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
For Loop
While Loop
while (condition) {
// code block to be executed
}
Do While Loop
A do while loop is executed at least once despite the condition being true or false
do {
// run this code in block
i++;
} while (condition);
Strings
The string is a sequence of characters that is used for storing and managing text data.
charAt method
str.charAt(3)
concat method
str1.concat(str2)
index of method
Returns the index of the first occurrence of the specified character from the string else -1 if not
found.
str.indexOf('substr')
match method
str.match(/(chapter \d+(\.\d)*)/i;)
replace method
Searches a string for a match against a specified string or char and returns a new string by
replacing the specified values.
str1.replace(str2)
search method
str.search('term')
split method
Splits a string into an array consisting of substrings.
str.split('\n')
substring method
str.substring(0,5)
Arrays
The array is a collection of data items of the same type. In simple terms, it is a variable that
contains multiple values.
variable
concat method
concat()
indexOf method
indexOf()
join method
join()
pop method
pop()
reverse method
reverse()
sort method
sort()
toString method
toString()
valueOf method
returns the relevant Number Object holding the value of the argument passed
valueOf()
Number Methods
JS math and number objects provide several constant and methods to perform mathematical
operations.
toExponential method
toExponential()
toPrecision method
toPrecision()
toString method
toString()
valueOf method
valueOf()
Maths Methods
ceil method
Rounds a number upwards to the nearest integer, and returns the result
ceil(x)
exp method
exp(x)
log method
log(x)
pow method
Returns the value of x to the power y.
pow(x,y)
random method
random()
sqrt method
sqrt(x)
Dates
Date object is used to get the year, month and day. It has methods to get and set day, month,
year, hour, minute, and seconds.
getDate()
getDay()
getHours()
Pulling Minutes from the Date object
getMinutes()
getSeconds()
getTime()
Mouse Events
Any change in the state of an object is referred to as an Event. With the help of JS, you can
handle events, i.e., how any specific HTML tag will work when the user does something.
click
element.addEventListener('click', ()=>{
// Code to be executed when the event is fired
});
oncontextmenu
element.addEventListener('contextmenu', ()=>{
// Code to be executed when the event is fired
});
dblclick
Fired when an element is double-clicked
element.addEventListener('dblclick', ()=>{
// Code to be executed when the event is fired
});
mouseenter
element.addEventListener('mouseenter', ()=>{
// Code to be executed when the event is fired
});
mouseleave
element.addEventListener('mouseleave', ()=>{
// Code to be executed when the event is fired
});
mousemove
element.addEventListener('mousemove', ()=>{
// Code to be executed when the event is fired
});
Keyboard Events
keydown
element.addEventListener('keydown', ()=>{
// Code to be executed when the event is fired
});
keypress
element.addEventListener('keypress', ()=>{
// Code to be executed when the event is fired
});
keyup
element.addEventListener('keyup', ()=>{
// Code to be executed when the event is fired
});
Errors
Errors are thrown by the compiler or interpreter whenever they find any fault in the code, and it
can be of any type like syntax error, run-time error, logical error, etc. JS provides some functions
to handle the errors.
Try the code block and execute catch when err is thrown
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
Window Methods
Methods that are available from the window object
alert method
Used to alert something on the screen
alert()
blur method
blur()
setInter val
setInterval(() => {
// Code to be executed
}, 1000);
setTimeout
setTimeout(() => {
// Code to be executed
}, 1000);
close
window.close()
confirm
The window.confirm() instructs the browser to display a dialog with an optional message, and to
wait until the user either confirms or cancels
open
Opens a new window
window.open("https://www.youtube.com");
prompt
Prompts the user with a text and takes a value. Second parameter is the default value
scrollBy
scrollTo
clearInter val
clearInterval(var)
clearTimeout
clearTimeout(var)
stop
stop()
Query/Get Elements
The browser creates a DOM (Document Object Model) whenever a web page is loaded, and with
the help of HTML DOM, one can access and modify all the elements of the HTML document.
quer ySelector
document.querySelector('css-selectors')
quer ySelectorAll
document.querySelectorAll('css-selectors', ...)
getElementsByTagName
document.getElementsByTagName('element-name')
getElementsByClassName
document.getElementsByClassName('class-name')
Get Element by Id
document.getElementById('id')
Creating Elements
Create new elements in the DOM
createElement
Create a new element
document.createElement('div')
createTextNode