Javascript Cheatsheet

by anupmaurya

JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm. It has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions.

It also called as is the Programming Language for the Web. JavaScript can update and change both HTML and CSS. JavaScript can calculate, manipulate and validate data.

Data Types

Javascript is a dynamically typed language and hence though there are data types, variables are not bound to them.

Data TypeDescription
numberRepresents numbers like integers, floating-values etc
stringRepresents one or more characters
bigintRepresents integers of arbitrary length
nullRepresents unknown values
undefinedRepresents undefined values
objectRepresents complex data structures
booleanRepresents either true or false


varVar is used to declare variables(old way of declaring variables)Function or global scope
letlet is also used to declare variables(new way)Global or block Scope
constconst is used to declare const values. Once the value is assigned it can not be modifiedGlobal or block Scope
let variable-name; // Just declaration let variable-name = value; // declaring variable and assigning it with some value let var1 = value1, var2 = value2, var3 = value3; // multiple variables declaration with their assigned values
Code language: JavaScript (javascript)


On page script

<script type="text/javascript"> ... </script>
Code language: HTML, XML (xml)

To include external javascript file

<script src="filename.js"></script>
Code language: HTML, XML (xml)


  • Single line comments – //
  • Multi line comments – /* */


console.log("hello"); // to display message to the browser console document.write(x); // to write to HTML prompt("Your name?","friend"); // input dialog. Second argument is the initial value alert(x); // writes in an alert box
Code language: JavaScript (javascript)

Strict mode

"use strict"; // throw errors for some of javascript silent errors and tells browser to be more strict.
Code language: JavaScript (javascript)

Conditional Statements


let age = 20; if (age > 18) { console.log('Adult'); }
Code language: JavaScript (javascript)


let age=7; if(age<0) { console.log('invalid age'); } else if (age<5 && age >0) { console.log('Infant'); } else if (age>=5 && age<=18) { console.log('child'); } else if (age>18) { console.log("Adult"); }
Code language: JavaScript (javascript)


// what is hello in different languages let language = "italian"; switch(language){ case "french" : console.log('BONJOUR'); break; case "spanish": console.log('Hola'); break; case "hindi" : console.log("Namaste"); break; default: console.log('Hello'); }
Code language: JavaScript (javascript)



console.log('simple for loop'); for(let i=1;i<=10;i++) { console.log(i); }
Code language: JavaScript (javascript)

let info = { name: "foo", id: 123 } for (let x in info) { console.log(x); <em>// prints keys of info which are name and id</em> }
Code language: JavaScript (javascript)


let mobiles = [ "iPhone", "Samsung", "OnePlus", "Pixel"]; for(let mbl of mobiles) { console.log(mbl); }
Code language: JavaScript (javascript)


let i=1; while(i<=10) { console.log(i); i++; }
Code language: JavaScript (javascript)


let i=1; do { console.log(i); i++; } while(i<=10);
Code language: JavaScript (javascript)


Arithmetic Operators+ – * / % ++ —
Comparision Operators== === != !== > >= < <=
Bitwise Operators& ^ | ^ ~ << >> >>>
Logical Operators&& || !
Assignment Operators= += -= *= /= %=
Special Operators? :,, new, typeof, void, yield, delete, in, instanceof


let arrayName = [value1, value2,..etc]; // or let arrayName = new Array("value1","value2",..etc);
Code language: JavaScript (javascript)

Array Methods

Method nameSyntax
forEach()arrayname.forEach(function(err, doc){ //code });
map(), doc)){ //code });
filter()arrayName.filter(function(err, doc)) { //code });
reduce()arrayName.reduce(function(err, doc)) { //code });
find()arrayName.find(function(err, doc)) { //code });
from()Array.from(arrayLike[, mapFn[, thisArg]]);
every()Array.every(callback(element[, index[, array]])[, thisArg])
some()Array.some(callback(element[, index[, array]])[, thisArg])
includes()arrayName.includes(value-to-be-checked[, starting-search-index])


// declaring a function function function-name(parameters){ // here parameters are optional //code } function-name(parameters); // calling a function
Code language: PHP (php)

Arrow function

(argument-list) => expression
Code language: PHP (php)


let sum= (a,b,c) => { return a+b+c; } console.log(sum(10,20,30));
Code language: JavaScript (javascript)


String Methods

Method NameUsage
slice(start,end)let sub-str=str.slice(starting position,ending position);
substring(start,endlet sub-str=str.substring(starting position,ending position);
substr(start,length)let sub-str=str.substr(starting position,length);
trim()let str1= str.trim();
charAt()let c=str.charAt(position);
charCodeAt()let c=str.charCodAt(position);
split()let array=str.split(“”);
lengthlet vln = str.length()
indexOf()let index=str.indexOf(“sub-string”);
lastIndexOf()let index=str.lastIndexOf(“sub-string”);
toUpperCase()let str1=str.toUpperCase();
toLowerCase()let str1=str.toLowerCase();
replace()let x=str.replace(“string to replace”,”replacement string”)
concat()let str3=str1.concat(” “,str2);

Number related Methods

Method NameUsage
toString()let x = num.toString();
toFixed()let x=num.toFixed(no of decimals)
toExponential()let x=num.toExponential();
toPrecision()let x=num.toPrecision(length)
valueOf()let x= num.valueOf();

Date Methods

considering date = new Date() for the below methods.

getDay()date.getDay()returns day as number 0 to 6 now = date and time
getFullYear()date.getFullYear();returns yyyy i.e., 2020
setFullYear()let year = date.setFullYear(2020);sets year as 2020
getMonth()date.getMonth();returns month as a number (0-11)
setMonth()let month = date.setMonth(10);sets month as 10 means november
getDate()date.getDate();retuns date as number 1 to 31
setDate()let day = date.setDate(20);sets date as 20
getHours()date.getHours();to get the hour (0-23)
setHours()let hrs = date.setHours(20);to set the hour (0-23)
getMinutes()date.getMinutes();to get the minute (0-59)
setMinutes()let min = date.setMinutes(40);to set the minutes (0-59)
getSeconds()date.getSeconds();to get the second (0-59)
setSeconds()let sec = date.setSeconds(30);to set the seconds (0-59)
getMilliseconds()date.getMilliseconds();to get the millisecond (0-999)
setMilliseconds()let milli = date.setMilliseconds(500);to set the milliseconds (0-999)
setTime()let dateTime = date.setTime(1582268856705);to set the time (milliseconds since January 1, 1970)
getTime()date.getTime()to get the time (milliseconds since January 1, 1970)

Math functions

Math.PI;returns pi value 3.141592653589793
Math.round(10.4);returns 10
Math.round(10.5);returns 5
Math.pow(2,3);returns 8 which is 2 to the power of 3
Math.sqrt(100);returns 10
Math.abs(-5.3);returns 5.3
Math.ceil(22.12);returns 23 by rounding up
Math.floor(22.92);returns 22 by rounding down
Math.min(2, 5, -7, 3);returns the lowest value which is -7
Math.max(2, 5, -7, 3);returns the highest value which is 5
Math.log(1);returns log value as 0
Math.random();returns a random number between 0 and 1
Math.sin(0);returns 0
Math.cos(Math.PI);to use tan,atan,asin,acos


let promise = new Promise(function(resolve, reject){ //code });
Code language: JavaScript (javascript)



async function functioname(parameters){ //code }
Code language: JavaScript (javascript)


async getTodos(userObj){ const res = await fetch([url]); const data = await res.json() return data; } let data = await getTodos({fn: "foo"});
Code language: JavaScript (javascript)

Error Handling

try { //code } catch(err) { //code }
Code language: JavaScript (javascript)

throw error

throw "Error message"; // throw error text to user
Code language: JavaScript (javascript)

Regular expressions


gPerforms a global match and finds all
iPerforms case-insensitive matching
mPerforms multiline matching

You may also like