JavaScript
A JavaScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.
# Getting Started
Introduction
JavaScript is a lightweight, interpreted programming language.
JSON cheatsheet ([Link])
Regex in JavaScript ([Link])
Console
// => Hello world!
[Link]('Hello world!');
// => Hello [Link]
[Link]('hello %s', '[Link]');
// Prints error message to stderr
[Link](new Error('Oops!'));
Numbers
let amount = 6;
let price = 4.99;
Variables
let x = null;
let name = "Tammy";
const found = false;
// => Tammy, false, null
[Link](name, found, x);
var a;
[Link](a); // => undefined
Strings
let single = 'Wheres my bandit hat?';
let double = "Wheres my bandit hat?";
// => 21
[Link]([Link]);
Arithmetic Operators
5 + 5 = 10 // Addition
10 - 5 = 5 // Subtraction
5 * 10 = 50 // Multiplication
10 / 5 = 2 // Division
10 % 5 = 0 // Modulo
Comments
// This line will denote a comment
/*
The below configuration must be
changed before deployment.
*/
Assignment Operators
let number = 100;
// Both statements will add 10
number = number + 10;
number += 10;
[Link](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;
[Link](count); // => undefined
count = 10;
[Link](count); // => 10
const Keyword
const numberOfColumns = 4;
// TypeError: Assignment to constant...
numberOfColumns = 8;
# JavaScript Conditionals
if Statement
const isMailSent = true;
if (isMailSent) {
[Link]('Mail sent to recipient');
}
Ternary Operator
var x=1;
Operators
true || false; // true
10 > 5 || 10 > 20; // true
false || false; // false
10 > 100 || 10 > 20; // false
Logical Operator &&
true && true; // true
1 > 2 && 2 > 1; // false
true && false; // false
4 === 4 && 3 > 1; // true
Comparison Operators
1 > 3 // false
3 > 1 // true
250 >= 250 // true
1 === 1 // true
1 === 2 // false
1 === '1' // false
Logical Operator !
let lateToWork = true;
let oppositeValue = !lateToWork;
// => false
[Link](oppositeValue);
Nullish coalescing operator ??
null ?? 'I win'; // 'I win'
undefined ?? 'Me too'; // 'Me too'
false ?? 'I lose' // false
0 ?? 'I lose again' // 0
else if
const size = 10;
if (size > 100) {
[Link]('Big');
} else if (size > 20) {
[Link]('Medium');
} else if (size > 4) {
[Link]('Small');
} else {
[Link]('Tiny');
}
// Print: Small
switch Statement
const food = 'salad';
switch (food) {
case 'oyster':
[Link]('The taste of the sea');
break;
case 'pizza':
[Link]('A delicious pie');
break;
default:
[Link]('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
'0' == false // true
'0' === false // false
The == just check the value, === check both the value and the type.
# JavaScript Functions
Functions
// Defining the function:
function sum(num1, num2) {
return num1 + num2;
}
// Calling the function:
sum(3, 6); // 9
Anonymous Functions
// Named function
function rocketToMars() {
return 'BOOM!';
}
// Anonymous function
const rocketToMars = function() {
return 'BOOM!';
}
Arrow Functions (ES6)
With two arguments
const sum = (param1, param2) => {
return param1 + param2;
};
[Link](sum(2,5)); // => 7
With no arguments
const printHello = () => {
[Link]('hello');
};
printHello(); // => hello
With a single argument
const checkWeight = weight => {
[Link](`Weight : ${weight}`);
};
checkWeight(25); // => Weight : 25
Concise arrow functions
const multiply = (a, b) => a * b;
// => 60
[Link](multiply(2, 30));
Arrow function available starting ES2015
return Keyword
// With return
function sum(num1, num2) {
return num1 + num2;
}
// The function doesn't output the sum
function sum(num1, num2) {
num1 + num2;
}
Calling Functions
// Defining the function
function sum(num1, num2) {
return num1 + num2;
}
// Calling the function
sum(2, 4); // 6
Function Expressions
const dog = function() {
return 'Woof!';
}
Function Parameters
// The parameter is name
function sayHello(name) {
return `Hello, ${name}!`;
}
Function Declaration
function add(num1, num2) {
return num1 + num2;
}
# JavaScript Scope
Scope
function myFunction() {
var pizzaName = "Margarita";
// Code here can use pizzaName
}
Block Scoped Variables
const isLoggedIn = true;
if (isLoggedIn == true) {
const statusMessage = 'Logged in.';
}
// Uncaught ReferenceError...
[Link](statusMessage);
Global Variables
// Variable declared globally
const color = 'blue';
function printColor() {
[Link](color);
}
printColor(); // => blue
let vs var
for (let i = 0; i < 3; i++) {
✔️
// This is the Max Scope for 'let'
// i accessible
// i not accessible ❌
}
✔️
for (var i = 0; i < 3; i++) {
// i accessible
✔️
}
// i accessible
var is scoped to the nearest function block, and let is scoped to the nearest enclosing block.
Loops with closures
// Prints 3 thrice, not what we meant.
for (var i = 0; i < 3; i++) {
setTimeout(_ => [Link](i), 10);
}
// Prints 0, 1 and 2, as expected.
for (let j = 0; j < 3; j++) {
setTimeout(_ => [Link](j), 10);
}
The variable has its own copy using let, and the variable has shared copy using var.
# JavaScript Arrays
Arrays
const fruits = ["apple", "orange", "banana"];
// Different data types
const data = [1, 'chicken', false];
Property .length
const numbers = [1, 2, 3, 4];
[Link] // 4
Index
// Accessing an array element
const myArray = [100, 200, 300];
[Link](myArray[0]); // 100
[Link](myArray[1]); // 200
Mutable chart
add remove start end
push ✔ ✔
pop ✔ ✔
unshift ✔ ✔
shift ✔ ✔
Method .push()
// Adding a single element:
const cart = ['apple', 'orange'];
[Link]('pear');
// Adding multiple elements:
const numbers = [1, 2];
[Link](3, 4, 5);
Add items to the end and returns the new array length.
Method .pop()
const fruits = ["apple", "orange", "banana"];
const fruit = [Link](); // 'banana'
[Link](fruits); // ["apple", "orange"]
Remove an item from the end and returns the removed item.
Method .shift()
let cats = ['Bob', 'Willy', 'Mini'];
[Link](); // ['Willy', 'Mini']
Remove an item from the beginning and returns the removed item.
Method .unshift()
let cats = ['Bob'];
// => ['Willy', 'Bob']
[Link]('Willy');
// => ['Puff', 'George', 'Willy', 'Bob']
[Link]('Puff', 'George');
Add items to the beginning and returns the new array length.
Method .concat()
const numbers = [3, 2, 1]
const newFirstNumber = 4
// => [ 4, 3, 2, 1 ]
[newFirstNumber].concat(numbers)
// => [ 3, 2, 1, 4 ]
[Link](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) {
[Link](i);
i++;
}
Reverse Loop
const fruits = ["apple", "orange", "banana"];
for (let i = [Link] - 1; i >= 0; i--) {
[Link](`${i}. ${fruits[i]}`);
}
// => 2. banana
// => 1. orange
// => 0. apple
Do…While Statement
x = 0
i = 0
do {
x = x + i;
[Link](x)
i++;
} while (i < 5);
// => 0 1 3 6 10
For Loop
for (let i = 0; i < 4; i += 1) {
[Link](i);
};
// => 0, 1, 2, 3
Looping Through Arrays
for (let i = 0; i < [Link]; i++){
[Link](array[i]);
}
// => Every item in the array
Break
for (let i = 0; i < 99; i += 1) {
if (i > 5) {
break;
}
[Link](i)
}
// => 0 1 2 3 4 5
Continue
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
Nested
for (let i = 0; i < 2; i += 1) {
for (let j = 0; j < 3; j += 1) {
[Link](`${i}-${j}`);
}
}
for...in loop
const fruits = ["apple", "orange", "banana"];
for (let index in fruits) {
[Link](index);
}
// => 0
// => 1
// => 2
for...of loop
const fruits = ["apple", "orange", "banana"];
for (let fruit of fruits) {
[Link](fruit);
}
// => apple
// => orange
// => banana
# JavaScript Iterators
Functions Assigned to Variables
let plusFive = (number) => {
return number + 5;
};
// f is assigned the value of plusFive
let f = plusFive;
plusFive(3); // 8
// Since f has a function value, it can be invoked.
f(9); // 14
Callback Functions
const isEven = (n) => {
return n % 2 == 0;
}
let printMsg = (evenFunc, num) => {
const isNumEven = evenFunc(num);
[Link](`${num} is an even number: ${isNumEven}.`)
}
// Pass in isEven as the callback function
printMsg(isEven, 4);
// => The number 4 is an even number: True.
Array Method .reduce()
const numbers = [1, 2, 3, 4];
const sum = [Link]((accumulator, curVal) => {
return accumulator + curVal;
});
[Link](sum); // 10
Array Method .map()
const members = ["Taylor", "Donald", "Don", "Natasha", "Bobby"];
const announcements = [Link]((member) => {
return member + " joined the contest.";
});
[Link](announcements);
Array Method .forEach()
const numbers = [28, 77, 45, 99, 27];
[Link](number => {
[Link](number);
});
Array Method .filter()
const randomNumbers = [4, 11, 42, 14, 39];
const filteredArray = [Link](n => {
# JavaScript Objects
Accessing Properties
const apple = {
color: 'Green',
price: { bulk: '$3/kg', smallQty: '$4/kg' }
};
[Link]([Link]); // => Green
[Link]([Link]); // => $3/kg
Naming Properties
// Example of invalid key names
const trainSchedule = {
// Invalid because of the space between words.
platform num: 10,
// Expressions cannot be keys.
40 - 10 + 2: 30,
// A + sign is invalid unless it is enclosed in quotations.
+compartment: 'C'
}
Non-existent properties
const classElection = {
date: 'January 12'
};
[Link]([Link]); // undefined
Mutable
const student = {
name: 'Sheldon',
score: 100,
grade: 'A',
}
[Link](student)
// { name: 'Sheldon', score: 100, grade: 'A' }
delete [Link]
[Link] = 'F'
[Link](student)
// { name: 'Sheldon', grade: 'F' }
student = {}
// TypeError: Assignment to constant variable.
Assignment shorthand syntax
const person = {
name: 'Tom',
age: '22',
};
const {name, age} = person;
[Link](name); // 'Tom'
[Link](age); // '22'
Delete operator
const person = {
firstName: "Matilda",
age: 27,
hobby: "knitting",
goal: "learning JavaScript"
};
delete [Link]; // or delete person[hobby];
[Link](person);
/*
{
firstName: "Matilda"
age: 27
goal: "learning JavaScript"
}
*/
Objects as arguments
const origNum = 8;
const origObj = {color: 'blue'};
const changeItUp = (num, obj) => {
num = 7;
[Link] = 'red';
};
changeItUp(origNum, origObj);
// Will output 8 since integers are passed by value.
[Link](origNum);
// Will output 'red' since objects are passed
// by reference and are therefore mutable.
[Link]([Link]);
Shorthand object creation
const activity = 'Surfing';
const beach = { activity };
[Link](beach); // { activity: 'Surfing' }
this Keyword
const cat = {
name: 'Pipey',
age: 8,
whatName() {
return [Link]
}
};
[Link]([Link]()); // => Pipey
Factory functions
// A factory function that accepts 'name',
// 'age', and 'breed' parameters to return
// a customized dog object.
const dogFactory = (name, age, breed) => {
return {
name: name,
age: age,
breed: breed,
bark() {
[Link]('Woof!');
}
};
};
Methods
const engine = {
// method shorthand, with one argument
start(adverb) {
[Link](`The engine starts up ${adverb}...`);
},
// anonymous arrow function expression with no arguments
sputter: () => {
[Link]('The engine sputters...');
},
};
[Link]('noisily');
[Link]();
Getters and setters
const myCat = {
_name: 'Dottie',
get name() {
return this._name;
},
set name(newName) {
this._name = newName;
}
};
// Reference invokes the getter
[Link]([Link]);
// Assignment invokes the setter
[Link] = 'Yankee';
# JavaScript Classes
Static Methods
class Dog {
constructor(name) {
this._name = name;
}
introduce() {
[Link]('This is ' + this._name + ' !');
}
// A static method
static bark() {
[Link]('Woof!');
}
}
const myDog = new Dog('Buster');
[Link]();
// Calling the static method
Class
class Song {
constructor() {
[Link];
[Link];
}
play() {
[Link]('Song playing!');
}
}
const mySong = new Song();
[Link]();
Class Constructor
class Song {
constructor(title, artist) {
[Link] = title;
[Link] = artist;
}
}
const mySong = new Song('Bohemian Rhapsody', 'Queen');
[Link]([Link]);
Class Methods
class Song {
play() {
[Link]('Playing!');
}
stop() {
[Link]('Stopping!');
}
}
extends
// Parent class
class Media {
constructor(info) {
[Link] = [Link];
[Link] = [Link];
}
}
// Child class
class Song extends Media {
constructor(songData) {
super(songData);
[Link] = [Link];
}
}
const mySong = new Song({
artist: 'Queen',
name: 'Bohemian Rhapsody',
publishDate: 1975
# JavaScript Modules
Export
// [Link]
// 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
}
Import
// [Link]
import add, { subtract, multiply, duplicate } from './[Link]';
[Link](add(6, 2)); // 8
[Link](subtract(6, 2)) // 4
[Link](multiply(6, 2)); // 12
[Link](duplicate(5)) // 10
// [Link]
<script type="module" src="[Link]"></script>
Export Module
// [Link]
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
}
// Multiple exports in [Link]
[Link] = {
add,
subtract,
multiply,
duplicate
}
Require Module
// [Link]
const myMath = require('./[Link]')
[Link]([Link](6, 2)); // 8
[Link]([Link](6, 2)) // 4
[Link]([Link](6, 2)); // 12
[Link]([Link](5)) // 10
# JavaScript Promises
Promise states
const promise = new Promise((resolve, reject) => {
const res = true;
// An asynchronous operation.
if (res) {
resolve('Resolved!');
}
else {
reject(Error('Error'));
}
});
Executor function
const executorFn = (resolve, reject) => {
resolve('Resolved!');
};
const promise = new Promise(executorFn);
setTimeout()
const loginAlert = () =>{
[Link]('Login');
};
setTimeout(loginAlert, 6000);
.then() method
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Result');
}, 200);
});
[Link]((res) => {
[Link](res);
}, (err) => {
[Link](err);
});
.catch() method
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
reject(Error('Promise Rejected Unconditionally.'));
}, 1000);
});
[Link]((res) => {
[Link](value);
});
[Link]((err) => {
[Link](err);
});
[Link]()
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3);
}, 300);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 200);
});
[Link]([promise1, promise2]).then((res) => {
[Link](res[0]);
[Link](res[1]);
});
Avoiding nested Promise and .then()
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('*');
}, 1000);
});
const twoStars = (star) => {
return (star + star);
};
const oneDot = (star) => {
return (star + '.');
};
const print = (val) => {
[Link](val);
};
// Chaining them all together
[Link](twoStars).then(oneDot).then(print);
Creating
const executorFn = (resolve, reject) => {
[Link]('The executor function of the promise!');
};
const promise = new Promise(executorFn);
Chaining multiple .then()
const promise = new Promise(resolve => setTimeout(() => resolve('dAlan'), 100));
[Link](res => {
return res === 'Alan' ? [Link]('Hey Alan!') : [Link]('Who are you?')
}).then((res) => {
[Link](res)
}, (err) => {
[Link](err)
});
Fake http Request with Promise
const mock = (success, timeout = 1000) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if(success) {
resolve({status: 200, data:{}});
} else {
reject({message: 'Error'});
}
}, timeout);
});
}
const someEvent = async () => {
try {
await mock(true, 1000);
} catch (e) {
[Link]([Link]);
}
}
# JavaScript Async-Await
Asynchronous
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
const msg = async function() { //Async Function Expression
const msg = await helloWorld();
[Link]('Message:', msg);
}
const msg1 = async () => { //Async Arrow Function
const msg = await helloWorld();
[Link]('Message:', msg);
}
msg(); // Message: Hello World! <-- after 2 seconds
msg1(); // Message: Hello World! <-- after 2 seconds
Resolving Promises
let pro1 = [Link](5);
let pro2 = 44;
let pro3 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'foo');
});
[Link]([pro1, pro2, pro3]).then(function(values) {
[Link](values);
});
Async Await Promises
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
async function msg() {
const msg = await helloWorld();
[Link]('Message:', msg);
}
msg(); // Message: Hello World! <-- after 2 seconds
Error Handling
let json = '{ "age": 30 }'; // incomplete data
try {
let user = [Link](json); // <-- no errors
[Link]( [Link] ); // no name!
} catch (e) {
console error( "Invalid JSON data!" );
Aysnc await operator
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
async function msg() {
const msg = await helloWorld();
[Link]('Message:', msg);
}
msg(); // Message: Hello World! <-- after 2 seconds
# JavaScript Requests
JSON
const jsonObj = {
"name": "Rick",
"id": "11A",
"level": 4
};
Also see: JSON cheatsheet
XMLHttpRequest
const xhr = new XMLHttpRequest();
[Link]('GET', '[Link]/getjson');
XMLHttpRequest is a browser-level API that enables the client to script data transfers via JavaScript, NOT part of the JavaScript language.
GET
const req = new XMLHttpRequest();
[Link] = 'json';
[Link]('GET', '/getdata?id=65');
[Link] = () => {
[Link]([Link]);
};
[Link]();
POST
const data = {
fish: 'Salmon',
weight: '1.5 KG',
units: 5
};
const xhr = new XMLHttpRequest();
[Link]('POST', '/inventory/add');
[Link] = 'json';
[Link]([Link](data));
[Link] = () => {
fetch api
fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json',
'apikey': apiKey
},
body: data
}).then(response => {
if ([Link]) {
return [Link]();
}
throw new Error('Request failed!');
}, networkError => {
[Link]([Link])
})
}
JSON Formatted
fetch('url-that-returns-JSON')
.then(response => [Link]())
.then(jsonResponse => {
[Link](jsonResponse);
});
promise url parameter fetch api
fetch('url')
.then(
response => {
[Link](response);
},
rejection => {
[Link]([Link]);
);
Fetch API Function
fetch('[Link] {
method: 'POST',
body: [Link]({id: "200"})
}).then(response => {
if([Link]){
return [Link]();
}
throw new Error('Request failed!');
}, networkError => {
[Link]([Link]);
}).then(jsonResponse => {
[Link](jsonResponse);
})
async await syntax
const getSuggestions = async () => {
const wordQuery = [Link];
const endpoint = `${url}${queryParams}${wordQuery}`;
try{
const response = await fetch(endpoint, {cache: 'no-cache'});
if([Link]){
const jsonResponse = await [Link]()
}
}
catch(error){
[Link](error)
}
}