JavaScript Cheat Sheet & Quick Reference
JavaScript Cheat Sheet & Quick Reference
JavaScript
A JavaScript cheat sheet with the most important concepts, functions, methods, and more. A
complete quick reference for beginners.
# Getting Started
Introduction
Console
Numbers
let amount = 6;
let price = 4.99;
https://quickref.me/javascript.html 1/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
Variables
let x = null;
let name = "Tammy";
const found = false;
var a;
console.log(a); // => undefined
Strings
// => 21
console.log(single.length);
Arithmetic Operators
5 + 5 = 10 // Addition
10 - 5 = 5 // Subtraction
5 * 10 = 50 // Multiplication
10 / 5 = 2 // Division
10 % 5 = 0 // Modulo
Comments
/*
The below configuration must be
changed before deployment.
*/
Assignment Operators
https://quickref.me/javascript.html 2/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
console.log(number);
// => 120
String Interpolation
let age = 7;
// String concatenation
'Tommy is ' + age + ' years old.';
// String interpolation
`Tommy is ${age} years old.`;
let Keyword
let count;
console.log(count); // => undefined
count = 10;
console.log(count); // => 10
const Keyword
const numberOfColumns = 4;
# JavaScript Conditionals
if Statement
if (isMailSent) {
https://quickref.me/javascript.html 3/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
Ternary Operator
var x=1;
// => true
result = (x == 1) ? true : false;
Operators
Comparison Operators
1 > 3 // false
3 > 1 // true
250 >= 250 // true
1 === 1 // true
1 === 2 // false
1 === '1' // false
Logical Operator !
// => false
console.log(oppositeValue);
https://quickref.me/javascript.html 4/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
else if
switch Statement
switch (food) {
case 'oyster':
console.log('The taste of the sea');
break;
case 'pizza':
console.log('A delicious pie');
break;
default:
console.log('Enjoy your meal');
}
== vs ===
0 == false // true
0 === false // false, different type
1 == "1" // true, automatic type conversion
1 === "1" // false, different type
null == undefined // true
null === undefined // false
https://quickref.me/javascript.html 5/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
# JavaScript Functions
Functions
Anonymous Functions
// Named function
function rocketToMars() {
return 'BOOM!';
}
// Anonymous function
const rocketToMars = function() {
return 'BOOM!';
}
With no arguments
https://quickref.me/javascript.html 6/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
return Keyword
// With return
function sum(num1, num2) {
return num1 + num2;
}
Calling Functions
Function Expressions
https://quickref.me/javascript.html 7/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
Function Parameters
Function Declaration
# JavaScript Scope
Scope
function myFunction() {
if (isLoggedIn == true) {
const statusMessage = 'Logged in.';
}
// Uncaught ReferenceError...
https://quickref.me/javascript.html 8/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
console.log(statusMessage);
Global Variables
function printColor() {
console.log(color);
}
let vs var
var is scoped to the nearest function block, and let is scoped to the nearest enclosing block.
The variable has its own copy using let, and the variable has shared copy using var.
https://quickref.me/javascript.html 9/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
# JavaScript Arrays
Arrays
Property .length
numbers.length // 4
Index
console.log(myArray[0]); // 100
console.log(myArray[1]); // 200
Mutable chart
push ✔ ✔
pop ✔ ✔
unshift ✔ ✔
shift ✔ ✔
Method .push()
Add items to the end and returns the new array length.
Method .pop()
Remove an item from the end and returns the removed item.
Method .shift()
Remove an item from the beginning and returns the removed item.
Method .unshift()
Add items to the beginning and returns the new array length.
Method .concat()
// => [ 4, 3, 2, 1 ]
[newFirstNumber].concat(numbers)
https://quickref.me/javascript.html 11/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
// => [ 3, 2, 1, 4 ]
numbers.concat(newFirstNumber)
if you want to avoid mutating your original array, you can use concat.
# JavaScript Loops
While Loop
while (condition) {
// code block to be executed
}
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Reverse Loop
// => 2. banana
// => 1. orange
// => 0. apple
Do…While Statement
x = 0
i = 0
do {
x = x + i;
https://quickref.me/javascript.html 12/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
console.log(x)
i++;
} while (i < 5);
// => 0 1 3 6 10
For Loop
// => 0, 1, 2, 3
Break
Continue
Nested
https://quickref.me/javascript.html 13/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
}
}
for...in loop
for...of loop
# JavaScript Iterators
Functions Assigned to Variables
plusFive(3); // 8
// Since f has a function value, it can be invoked.
f(9); // 14
https://quickref.me/javascript.html 14/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
Callback Functions
console.log(sum); // 10
console.log(announcements);
numbers.forEach(number => {
console.log(number);
});
https://quickref.me/javascript.html 15/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
# JavaScript Objects
Accessing Properties
const apple = {
color: 'Green',
price: { bulk: '$3/kg', smallQty: '$4/kg' }
};
console.log(apple.color); // => Green
console.log(apple.price.bulk); // => $3/kg
Naming Properties
Non-existent properties
const classElection = {
date: 'January 12'
};
console.log(classElection.place); // undefined
Mutable
https://quickref.me/javascript.html 16/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
const student = {
name: 'Sheldon',
score: 100,
grade: 'A',
}
console.log(student)
// { name: 'Sheldon', score: 100, grade: 'A' }
delete student.score
student.grade = 'F'
console.log(student)
// { name: 'Sheldon', grade: 'F' }
student = {}
// TypeError: Assignment to constant variable.
const person = {
name: 'Tom',
age: '22',
};
const {name, age} = person;
console.log(name); // 'Tom'
console.log(age); // '22'
Delete operator
const person = {
firstName: "Matilda",
age: 27,
hobby: "knitting",
goal: "learning JavaScript"
};
console.log(person);
/*
{
firstName: "Matilda"
age: 27
https://quickref.me/javascript.html 17/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
Objects as arguments
const origNum = 8;
const origObj = {color: 'blue'};
changeItUp(origNum, origObj);
this Keyword
const cat = {
name: 'Pipey',
age: 8,
whatName() {
return this.name
}
};
console.log(cat.whatName()); // => Pipey
Factory functions
https://quickref.me/javascript.html 18/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
Methods
const engine = {
// method shorthand, with one argument
start(adverb) {
console.log(`The engine starts up ${adverb}...`);
},
// anonymous arrow function expression with no arguments
sputter: () => {
console.log('The engine sputters...');
},
};
engine.start('noisily');
engine.sputter();
const myCat = {
_name: 'Dottie',
get name() {
return this._name;
},
set name(newName) {
this._name = newName;
}
};
console.log(myCat.name);
# JavaScript Classes
Static Methods
class Dog {
constructor(name) {
this._name = name;
}
introduce() {
console.log('This is ' + this._name + ' !');
}
// A static method
static bark() {
console.log('Woof!');
}
}
Class
class Song {
constructor() {
this.title;
this.author;
}
play() {
https://quickref.me/javascript.html 20/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
console.log('Song playing!');
}
}
Class Constructor
class Song {
constructor(title, artist) {
this.title = title;
this.artist = artist;
}
}
Class Methods
class Song {
play() {
console.log('Playing!');
}
stop() {
console.log('Stopping!');
}
}
extends
// Parent class
class Media {
constructor(info) {
this.publishDate = info.publishDate;
this.name = info.name;
}
}
// Child class
class Song extends Media {
constructor(songData) {
https://quickref.me/javascript.html 21/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
super(songData);
this.artist = songData.artist;
}
}
# JavaScript Modules
Export
// myMath.js
// Default export
export default function add(x,y){
return x + y
}
// Normal export
export function subtract(x,y){
return x - y
}
// Multiple exports
function multiply(x,y){
return x * y
}
function duplicate(x){
return x * 2
}
export {
multiply,
duplicate
}
https://quickref.me/javascript.html 22/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
Import
// main.js
import add, { subtract, multiply, duplicate } from './myMath.js';
console.log(add(6, 2)); // 8
console.log(subtract(6, 2)) // 4
console.log(multiply(6, 2)); // 12
console.log(duplicate(5)) // 10
// index.html
<script type="module" src="main.js"></script>
Export Module
// myMath.js
function add(x,y){
return x + y
}
function subtract(x,y){
return x - y
}
function multiply(x,y){
return x * y
}
function duplicate(x){
return x * 2
}
Require Module
// main.js
const myMath = require('./myMath.js')
https://quickref.me/javascript.html 23/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
console.log(myMath.add(6, 2)); // 8
console.log(myMath.subtract(6, 2)) // 4
console.log(myMath.multiply(6, 2)); // 12
console.log(myMath.duplicate(5)) // 10
# JavaScript Promises
Promise states
Executor function
setTimeout()
setTimeout(loginAlert, 6000);
.then() method
https://quickref.me/javascript.html 24/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
promise.then((res) => {
console.log(res);
}, (err) => {
console.error(err);
});
.catch() method
promise.then((res) => {
console.log(value);
});
promise.catch((err) => {
console.error(err);
});
Promise.all()
https://quickref.me/javascript.html 25/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
console.log(res[1]);
});
Creating
promise.then(res => {
return res === 'Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you
}).then((res) => {
console.log(res)
}, (err) => {
https://quickref.me/javascript.html 26/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
console.error(err)
});
# JavaScript Async-Await
Asynchronous
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
Resolving Promises
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
Error Handling
https://quickref.me/javascript.html 28/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
try {
let user = JSON.parse(json); // <-- no errors
console.log( user.name ); // no name!
} catch (e) {
console.error( "Invalid JSON data!" );
}
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
# JavaScript Requests
JSON
const jsonObj = {
"name": "Rick",
"id": "11A",
"level": 4
};
XMLHttpRequest
https://quickref.me/javascript.html 29/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
xhr.open('GET', 'mysite.com/getjson');
XMLHttpRequest is a browser-level API that enables the client to script data transfers via JavaScript, NOT
t f th J S i t l
GET
req.send();
POST
const data = {
fish: 'Salmon',
weight: '1.5 KG',
units: 5
};
const xhr = new XMLHttpRequest();
xhr.open('POST', '/inventory/add');
xhr.responseType = 'json';
xhr.send(JSON.stringify(data));
xhr.onload = () => {
console.log(xhr.response);
};
fetch api
fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json',
'apikey': apiKey
},
body: data
}).then(response => {
if (response.ok) {
return response.json();
https://quickref.me/javascript.html 30/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
}
throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message)
})
}
JSON Formatted
fetch('url-that-returns-JSON')
.then(response => response.json())
.then(jsonResponse => {
console.log(jsonResponse);
});
fetch('url')
.then(
response => {
console.log(response);
},
rejection => {
console.error(rejection.message);
);
fetch('https://api-xxx.com/endpoint', {
method: 'POST',
body: JSON.stringify({id: "200"})
}).then(response => {
if(response.ok){
return response.json();
}
throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message);
}).then(jsonResponse => {
console.log(jsonResponse);
})
https://quickref.me/javascript.html 31/32
10/13/24, 6:04 PM JavaScript Cheat Sheet & Quick Reference
Related Cheatsheet
Recent Cheatsheet
https://quickref.me/javascript.html 32/32