In this comprehensive JavaScript cheat sheet, we've curated a collection of the most commonly used features, methods, and techniques, organized for easy navigation and quick reference. Whether you're brushing up on the basics or exploring advanced concepts, this cheat sheet will serve as your trusty companion on your JavaScript journey.
Why a cheat sheet?
In the fast-paced world of programming, having quick access to essential syntax, functions, and concepts can be a game-changer. That's where a JavaScript cheat sheet becomes invaluable. It serves as a handy reference, providing bite-sized information that helps streamline your coding process and tackle challenges with confidence.
Let's start
let's begin this cheat sheet
On page script
‹script type="text/javascript">
</script>
Include external JS file
<script src="filename.js"></script>
Functions
Named Function
function addNumbers(x, y) {
return x + y;
}
Arrow Functions
let sayHelloWorld = () => {
console.log('Hello World!');
}
sayHelloWorld(); // Hello World
Function hoisting
console.log(square(6)); // 36
function square(n) {
return n * n;
}
Map Function
const a = ["ABCD", "ABC", "ABCDEF", "AB"];
const length1 = a.map(function (s) {
return s.length;
});
console.log(length1); // [4, 3, 6, 2]
const length2 = a.map((s) => s.length);
console.log(length2); // [4, 3, 6, 2]
Comments
/ Multi line comment /
// One line
Logging/Print
console.log('I am billionaire.');
document.write('I love nature.');
alert("I am happy.");
confirm("Are you want to be billionaire?");
prompt("I am a quick learner?", "JavaScrip");
Data Types
var name = "James": // string
var age = 21; // number
var name = {first: "Harry", last: "Potter"}; // object
var IsIamHappy = true; // boolean
var countries = [ "Inda","USA", "UK"] // array
var b; typeof b; // undefined
var b = null; // value null
If - Else Statement
if (age >= 18) // logical condition here
{
status = "You can vote."; // executed if condition is true here
}
else //else block is optional
{
status = "You can't vote." //executed if condition is false here
}
For Loop
for (var i = 0; i < 10; i++) {
document.write(i +"<br/>")
}
While Loop
var i = 1;
while (i < 100) {
document. write(i +"<br/>");
i++;
}
Do - While Loop
var i = 1;
do {
document. write(i +"<br/>");
i++;
} while (i < 100)
For Each Loop
const numbers = [21,44,55,10];
numbers.forEach(num=>{
console.log(num * 2);
});
Numbers
var pi = 3.141;
Number(true); // converts to number
Number(new Date)) // number of milliseconds since 1970
pi.toFixed(0); // returns 3
pi.toFixed(2); // returns 3.14
pi.toPrecision (2) // returns 3.1
pi.valueof(); // returns number
Number.MAX_VALUE // largest possible JS number
Number.MIN_VALUE // smallest possible JS number
Number.NEGATIVE_INFINITY // -Infinity
Number.POSITIVE_INFINITY // Infinity
parseInt("3 months"); // returns the first number: 3
parseFloat("3.5 days"): // returns 3.5
Javascript Math
var pi = Math. PI; // 3.141592653589793
Math.random(); // random number between 0 and 1
Math.pow(2,8); // = 256 - 2 to the power of 8
Math.sqrt (49); // = 7 - square root
Math.abs (-3.14); // = 3.14 - absolute, positive value
Math.round (3.3); // = 3 - rounded
Math.round (3.5); // = 4
Math.ceil (3.14); // = 4 - rounded up
Math.floor (3.99); // = 3 - rounded down
Math.sin(0); // = 0 - sine
Math.cos (Math.PI); // OTHERS: tan, atan, asin, acos,
Math.min(0, 3, -2, 2); // = -2 - the lowest value
Math.max(0,3, -2, 2); // = 3 - the highest value
Math.log (1); // = 0 natural logarithm
Math.exp (1): // = 2.7182pOW(E, X)
Math.floor(Math.random() * 5) + 1; //1 random integer, from 1 to 5
Strings
var abc = "abcdefghijklmnopqrstuvwxyz";
var esc = 'I don't \n know'; // \n new line
var len = abc. length; // string length
abc.indexOf("pqr"); // find substring
abc.lastIndexOf("pqr"); // last occurance
abc.slice(7,10); // cuts out "hij",
abc.replace ("pqr", "123"); // find and replace
abc.toUpperCase: // convert to upper case
abc.toLowerCase); // convert to lower case
abc.concat(" ", str2); // abc + " " + str2
abc.charAt(2); character at index: "c"
abc[2]; // unsafe, abc[2] = "C" doesn't work
abc.charCodeAt (2) ; // character code at index: "c" -> 99
"Hello".search("e") => 1
"Hello".slice (1, 3) => el
"Hello"'split('''') => ['H', 'e', T', T', 'o']
128.toString (16); // number to hex(16), octal or binary
" Hello ".trim() => Hello
" Hello ".trimStart() => "Hello "
" Hello ".trimEnd() => " Hello"
"Hello".substring(2, 4) => ||
"Hello".repeat(3) => HelloHelloHello
"Hello".match (/[A-Z]/g) => ['H']
"Hello".padStart(6, "?") => ?Hello
"Hello".padEnd(6, "?") => Hello?
"Hello".startsWith("H") => true
"Hello".ends With("o") => true
"Hello".includes ("x") => false
"Hello".match (/[A-Z]/g) => ['H']
Array
const days = ['Sun', 'Tue', 'Wed', 'Thrus'];
// splice (startIndex, deleteCount, item)
days.splice (1, 0, 'Mon'); // ["Sun", "Mon", "Tue", "Wed", "Thrus"]
days.splice (4, 1, 'Fri'); // ["Sun", "Mon", "Tue", "Wed", "Fri"]
var arr = [1,2,3]; // Below operations are on new array arr= [1,2,3]
var x = arr.shift() //arr=[2,3], x=1
var x = arr.unshift (5) //arr=[5,1,2,3], x=4 \\
var x = arr.pop() //arr= [1,2], x=3
var x = arr.push(7) //arr=[1,2,3,7], x=4
['a', 'b'].concat(['c']); // ['a', 'b', 'c']
['a', 'b', 'c'].join('~'); // 'a~b~c'
['a', 'b', 'c'].slice(1); // ['b', 'c']
['a', 'b', 'b'].indexOf('b'); // 1
['a', 'b', 'b'].lastIndexOf('b'); // 2
[1,2,3].map(x => x * 2); // [2,4,6]
[1,2,3].reduce((x,y) => x * y); // 6
[1,3,2].sort(); // [1,2,3]
[1,2,3].reverse(); // [3,2,1]
[1,2,3].length; // 3
[1,2,3].every (x => x < 5); // true
[1,2,3,4].some (x => x < 3); // true
[1,2,3].filter(x => x < 2); // [1]
['a', 'b', 'c'].forEach (x => console.log(x)); // "a" "b" "c"
JavaScript Window
Location
Returns a location object that contains information about the current url
// reload the page after 2 seconds
setTimeout ( ()= {
window.Location.reload()
}, 2000)
History
Returns an history object that contains the pages visited by a user
// go back after 2 seconds
setTimeout ( ()= {
window.history.go (-1)
7, 2000)
// or
setTimeout (()= {
window.history.back()
J, 2000)
Document
Returns the document object as an html document loaded into a web browser
// get the title of the page
console.log(window.Document.Title)
// <title>my app</title> →> my app
// change the body of the page
window.document.body.innerHTML = "hello world"
Navigator
Returns and object containing information about the user's browser
// preferred language of the user
console.log(window. Navigator. language)
// get location coordinates
if (navigator-geolocation) {
window.navigator.geolocation.getCurrentPosition(pos =>
console. log (pos)
})
} else {
console.log("couldn't get the position")
}
Screen
Returns an object which contains the information about the user's screen
console.log(window.screen.height)
// 900
console.log(window.screen.width)
Local Storage
setItem()
Allows you to store values in the localStorage object; accepts 2 parameters: a key and a value.
window.localStorage.setItem('username','IamCkNitin');
If arrays or objects, then first convert into strings using JSON.stringify( ) As localStorage can only store strings.
const userNameAndPassword = {
username = "IamCkNitin",
Password = "DM@Me"
}
window.localStorage.setItem('login', JSON.stringify(userNameAndPassword)) ;
getItem( )
Allows you to access the data stored in localStorage. Simply pass key as the parameter and it will return value accordingly.
window.localStorage.getItem('cred');
// {"username": "IamCkNitin","password": "DM@Me"}, Use JSON. parse() to convert it back to object.
JSON. parse(window.localStorage.getItem('cred'));
removeItem( )
Allows you to remove the data stored in localStorage. Simply pass the key as the parameter, and it will remove both the key and value. (Does nothing when the parameter is left empty)
window.localStorage.removeItem('cred');
clear ()
Deletes every item in the localStorage.
window.localStorage.clear();
key ( )
Allows you to loop through the keys and pass an index as the parameter to retrieve the name of the key.
var obj = window.localStorage.key(index);
Date and Time
const today = new Date()
today // 2020-08-09T01:40:51.017Z
today.getDate() // 9
today.getDay() // 0 sunday
today.getMonth() // 7 (0 is jan)
today.getFullYear() // 2020
today.getYear() // 120 ?
today.getHours() // 11
today.getMinutes() // 40
today.getSeconds() // 51
today.getMilliseconds () // 24
today.getTime() // 1596937251025
today.getTimezoneOffset() // -600
today.setDate(5)
today.setMonth(5)
today.setFullYear(2022)
today.setYear(100)
today.setHours(12)
today.setMinutes(5)
today.setSeconds(8)
today.setMilliseconds(45)
today.setTime(34)
today.setUTCDate(11)
today.setUTCMonth(5)
today.setUTCFullYear(2022)
today.setUTCHours(5)
today.setUTCMinutes(10)
today.setUTCSeconds(24)
today.setUTCMilliseconds(22)
Date.parse('9 Aug 2020') // 1596895200000
Returns number
milliseconds since January 1, 1970 Returns NaN if invalid
let utcDate = new Date (Date. UTC (2020, 7, 9, 0, 0, 0));
utcDate // 2020-08-09T00:00:00.000Z
utcDate.valueOf() // 1596895200000 (same as parse)
today.getUTCDate() // 9
today.getUTCDay() // 0
today.getUTCMonth() // 7
today.getUTCFullYear() // 2020
today.getUTCHours() // 1
today.getUTCMinutes() // 40
today.getUTCSeconds() // 51
today.getUTCMilliseconds() // 31
const today = new Date()
today.toString() // 'Sun Aug 09 2020 16:44:29 GMT+1000
// (Australian Eastern Standard Time)'
today.toLocaleString() // '09/08/2020, 16:44:29'
today.toGMTString() // 'Sun, 09 Aug 2020 06:44:29 GMT'
today.toUTCString() // 'Sun, 09 Aug 2020 06:44:29 GMT'
JavaScript DOM mainuplation
//single element defined by id
const app = document.getElementById('app')
//multiple elements (arrays) defined by class name
const hero = document.getElementsByClassName('hero')
//multiple elements based on html tag
const h1 = document.getElementsByTagName('h1')
//first element based on selector
const hero = document.querySelector('.hero')
//multiple elements based on selector
const heroes = document.querySelectorAll('.hero')
//create html element of tag <p>
let para = document.createElement('p')
//create text node
let text = document.createTextNode('I ❤ it')
//add text node to the para element
para.appendChild(text)
//insert h2 before h1
app.insertBefore (h2, h1)
<p>I it</p>
h1.insertAdjacentHTML ('beforebegin',<span>cool</span>')
// beforebegin => placed before h1 as a sibling
// afterbegin => placed inside h1 as a first child
// beforeend => placed inside h1 as a last child
// afterend => placed after h1 as a sibling
<div id="app" class="hero dark">
<h1>Hello Javascript</h1>
</div>
app.classList.remove('dark') // remove class
app.classList.add('light') // add class
app.classList.toggle('visible') // toggle class
app.classList.contains('app') // true if app present
app.childNodes // retrieve all child nodes
app.parentNode // return parent node
Java Object
const obj = { key1: value1, key2: value2 }; //Create object
// Constructor Function
function ObjectName(prop1, prop2) {
this.prop1 = prop1;
this.prop2 = prop2;
}
const obj = new ObjectName(value1, value2);
// ES6 Class
class ClassName {
constructor(prop1, prop2) {
this.prop1 = prop1;
this.prop2 = prop2;
}
}
const obj = new ClassName(value1, value2);
//Accessing Object Properties
//Dot Notation
const value = obj.key;
//Bracket Notation (Useful for dynamic property access):
const key = 'key';
const value = obj[key];
//Modifying Object Properties
obj.key = newValue;
//Checking if Object has Property
if ('key' in obj) {
// Property exists
}
//Deleting Object Properties
delete obj.key;
//Looping Through Object Properties:
//For...in Loop
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
// Do something with key and value
}
}
//Object Methods
//Object.keys()
const keys = Object.keys(obj);
//Object.values()
const values = Object.values(obj);
//Object.entries()
const entries = Object.entries(obj);
//Object Comparison
const isEqual = JSON.stringify(obj1) === JSON.stringify(obj2);
//Object Destructuring
const { key1, key2 } = obj;
//Cloning Objects
//Shallow Clone
const cloneObj = { ...obj };
//Deep Clone (Using JSON)
const deepCloneObj = JSON.parse(JSON.stringify(obj));
//Merging Objects
//Object.assign()
const mergedObj = Object.assign({}, obj1, obj2);
//Freezing Objects (Prevent Modification)
Object.freeze(obj);
//Sealing Objects (Prevent Addition/Deletion of Properties)
Object.seal(obj);