JavaScript Cheat Sheet & Quick Reference
JavaScript Cheat Sheet & Quick Reference
ME
JavaScript
A JavaScript cheat sheet with the most important concepts, functions, methods, and more. A
complete quick reference for beginners.
# Getting started
Introduction
Console
console.log('Hello world!');
console.error(new Error('Oops!'));
Numbers
let amount = 6;
Variables
let x = null;
var a;
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
/*
*/
Assignment Operators
number += 10;
console.log(number);
// => 120
String Interpolation
let age = 7;
// String concatenation
// String interpolation
let Keyword
let count;
count = 10;
console.log(count); // => 10
const Keyword
const numberOfColumns = 4;
numberOfColumns = 8;
# JavaScript Conditionals
if Statement
if (isMailSent) {
Ternary Operator
var x=1;
// => true
Operators
true || false; // true
Comparison Operators
1 > 3 // false
3 > 1 // true
1 === 1 // true
1 === 2 // false
Logical Operator !
// => false
console.log(oppositeValue);
else if
console.log('Big');
console.log('Medium');
console.log('Small');
} else {
console.log('Tiny');
// Print: Small
switch Statement
switch (food) {
case 'oyster':
break;
case 'pizza':
break;
default:
== vs ===
0 == false // true
The == just check the value, === check both the value and the type.
# JavaScript Functions
Functions
sum(3, 6); // 9
Anonymous Functions
// Named function
function rocketToMars() {
return 'BOOM!';
// Anonymous function
return 'BOOM!';
};
console.log(sum(2,5)); // => 7
With no arguments
console.log('hello');
};
console.log(`Weight : ${weight}`);
};
// => 60
console.log(multiply(2, 30));
// With return
num1 + num2;
Calling Functions
sum(2, 4); // 6
Function Expressions
return 'Woof!';
Function Parameters
function sayHello(name) {
Function Declaration
# JavaScript Scope
Scope
function myFunction() {
if (isLoggedIn == true) {
// Uncaught ReferenceError...
console.log(statusMessage);
Global Variables
function printColor() {
console.log(color);
let vs var
// i accessible ✔️
// i not accessible ❌
// i accessible ✔️
// i accessible ✔️
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.
# JavaScript Arrays
Arrays
Property .length
numbers.length // 4
Index
console.log(myArray[0]); // 100
push ✔ ✔
pop ✔ ✔
unshift ✔ ✔
shift ✔ ✔
Method .push()
cart.push('pear');
numbers.push(3, 4, 5);
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()
cats.unshift('Willy');
cats.unshift('Puff', 'George');
Add items to the beginning and returns the new array length.
Method .concat()
const newFirstElement = 4
// => [ 4, 3, 2, 1 ]
[newFirstElement].concat(array)
// => [ 3, 2, 1, 4 ]
array.concat(newFirstElement)
if you want to avoid mutating your original array, you can use concat.
# JavaScript Loops
While Loop
while (condition) {
let i = 0;
while (i < 5) {
console.log(i);
i++;
Reverse Loop
console.log(`${i}. ${items[i]}`);
// => 2. cherry
// => 1. banana
Do…While Statement
x = 0
i = 0
do {
x = x + i;
console.log(x)
i++;
// => 0 1 3 6 10
For Loop
console.log(i);
};
// => 0, 1, 2, 3
console.log(array[i]);
Break
if (i > 5) {
break;
console.log(i)
// => 0 1 2 3 4 5
Continue
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
Nested
console.log(`${i}-${j}`);
for...in loop
console.log(`${key}: ${mobile[key]}`);
# JavaScript Iterators
Functions Assigned to Variables
return number + 5;
};
let f = plusFive;
plusFive(3); // 8
f(9); // 14
Callback Functions
return n % 2 == 0;
printMsg(isEven, 4);
});
console.log(sum); // 10
})
console.log(announcements);
numbers.forEach(number => {
console.log(number);
});
return n > 5;
});
# JavaScript Objects
Accessing Properties
const apple = {
color: 'Green',
};
Naming Properties
const trainSchedule = {
40 - 10 + 2: 30,
+compartment: 'C'
Non-existent properties
const classElection = {
};
console.log(classElection.place); // undefined
Mutable
const student = {
name: 'Sheldon',
score: 100,
grade: 'A',
console.log(student)
delete student.score
student.grade = 'F'
console.log(student)
student = {}
const person = {
name: 'Tom',
age: '22',
};
console.log(name); // 'Tom'
console.log(age); // '22'
Delete operator
const person = {
firstName: "Matilda",
age: 27,
hobby: "knitting",
};
console.log(person);
/*
firstName: "Matilda"
age: 27
*/
Objects as arguments
const origNum = 8;
num = 7;
obj.color = 'red';
};
changeItUp(origNum, origObj);
console.log(origNum);
console.log(origObj.color);
this Keyword
const cat = {
name: 'Pipey',
age: 8,
whatName() {
return this.name
};
Factory functions
return {
name: name,
age: age,
breed: breed,
bark() {
console.log('Woof!');
};
};
Methods
const engine = {
start(adverb) {
},
sputter: () => {
},
};
engine.start('noisily');
engine.sputter();
const myCat = {
_name: 'Dottie',
get name() {
return this._name;
},
set name(newName) {
this._name = newName;
};
console.log(myCat.name);
myCat.name = 'Yankee';
# JavaScript Classes
Static Methods
class Dog {
constructor(name) {
this._name = name;
introduce() {
// A static method
static bark() {
console.log('Woof!');
myDog.introduce();
Dog.bark();
Class
class Song {
constructor() {
this.title;
this.author;
play() {
console.log('Song playing!');
mySong.play();
Class Constructor
class Song {
constructor(title, artist) {
this.title = title;
this.artist = artist;
console.log(mySong.title);
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
constructor(songData) {
super(songData);
this.artist = songData.artist;
artist: 'Queen',
publishDate: 1975
});
# JavaScript Modules
Require
console.log(moduleA.someFunctionality)
Export
// module "moduleA.js"
return x * x * x;
// In main.js
console.log(cube(3)); // 27
Export Module
module.exports = Course;
Import keyword
// add.js
return x + y
// main.js
console.log(add(2, 3)); // 5
# JavaScript Promises
Promise states
// An asynchronous operation.
if (res) {
resolve('Resolved!');
else {
reject(Error('Error'));
});
Executor function
resolve('Resolved!');
};
setTimeout()
console.log('Login');
};
setTimeout(loginAlert, 6000);
.then() method
setTimeout(() => {
resolve('Result');
}, 200);
});
promise.then((res) => {
console.log(res);
}, (err) => {
console.error(err);
});
.catch() method
setTimeout(() => {
}, 1000);
});
promise.then((res) => {
console.log(value);
});
promise.catch((err) => {
console.error(err);
});
Promise.all()
setTimeout(() => {
resolve(3);
}, 300);
});
setTimeout(() => {
resolve(2);
}, 200);
});
console.log(res[0]);
console.log(res[1]);
});
setTimeout(() => {
resolve('*');
}, 1000);
});
};
};
console.log(val);
};
promise.then(twoStars).then(oneDot).then(print);
Creating
};
promise.then(res => {
console.log(res)
}, (err) => {
console.error(err)
});
# JavaScript Async-Await
Asynchronous
function helloWorld() {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
console.log('Message:', msg);
console.log('Message:', msg);
Resolving Promises
});
console.log(values);
});
function helloWorld() {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
console.log('Message:', msg);
Error Handling
try {
} catch (e) {
function helloWorld() {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
console.log('Message:', msg);
# JavaScript Requests
JSON
const jsonObj = {
"name": "Rick",
"id": "11A",
"level": 4
};
XMLHttpRequest
xhr.open('GET', 'mysite.com/getjson');
XMLHttpRequest is a browser-level API that enables the client to script data transfers via JavaScript,
NOT part of the JavaScript language.
GET
req.responseType = 'json';
req.open('GET', '/getdata?id=65');
req.onload = () => {
console.log(xhr.response);
};
req.send();
POST
const data = {
fish: 'Salmon',
units: 5
};
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();
}, networkError => {
console.log(networkError.message)
})
JSON Formatted
fetch('url-that-returns-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',
}).then(response => {
if(response.ok){
return response.json();
}, networkError => {
console.log(networkError.message);
}).then(jsonResponse => {
console.log(jsonResponse);
})
try{
if(response.ok){
catch(error){
console.log(error)
}
Related Cheatsheet
How to calculate the distance between two How to calculate the linear interpolation
points in JavaScript Cheatsheet between two numbers in JavaScript Cheatsheet
Quick Reference Quick Reference
Recent Cheatsheet