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;
Variables
[Link] 1/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
let x = null;
let name = "Tammy";
const found = false;
var a;
Strings
// => 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
/*
The below configuration must be
changed before deployment.
*/
Assignment Operators
[Link](number);
// => 120
[Link] 2/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
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;
# JavaScript Conditionals
if Statement
if (isMailSent) {
[Link]('Mail sent to recipient');
}
Ternary Operator
var x=1;
// => true
result = (x == 1) ? true : false;
[Link] 3/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
Operators
Comparison Operators
1 > 3 // false
3 > 1 // true
250 >= 250 // true
1 === 1 // true
1 === 2 // false
1 === '1' // false
Logical Operator !
// => false
[Link](oppositeValue);
else if
[Link] 4/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
[Link]('Medium');
} else if (size > 4) {
[Link]('Small');
} else {
[Link]('Tiny');
}
// Print: Small
switch Statement
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
[Link] 5/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
Anonymous Functions
// Named function
function rocketToMars() {
return 'BOOM!';
}
// Anonymous function
const rocketToMars = function() {
return 'BOOM!';
}
With no arguments
[Link] 6/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
return Keyword
// With return
function sum(num1, num2) {
return num1 + num2;
}
Calling Functions
Function Expressions
Function Parameters
Function Declaration
[Link] 7/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
# JavaScript Scope
Scope
function myFunction() {
if (isLoggedIn == true) {
const statusMessage = 'Logged in.';
}
// Uncaught ReferenceError...
[Link](statusMessage);
Global Variables
function printColor() {
[Link](color);
}
let vs var
✔️
// This is the Max Scope for 'let'
// i accessible
❌
}
// i not accessible
[Link] 8/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
✔️
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.
The variable has its own copy using let, and the variable has shared copy using var.
# JavaScript Arrays
Arrays
Property .length
[Link] // 4
Index
[Link] 9/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
[Link](myArray[0]); // 100
[Link](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()
[Link] 10/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
Method .concat()
// => [ 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
[Link] 11/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
// => 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
// => 0, 1, 2, 3
Break
Continue
[Link] 12/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
for...in loop
for...of loop
# JavaScript Iterators
Functions Assigned to Variables
let f = plusFive;
plusFive(3); // 8
// Since f has a function value, it can be invoked.
f(9); // 14
Callback Functions
[Link](sum); // 10
[Link](announcements);
[Link] 14/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
[Link](number => {
[Link](number);
});
# JavaScript Objects
Accessing Properties
const apple = {
color: 'Green',
price: { bulk: '$3/kg', smallQty: '$4/kg' }
};
[Link]([Link]); // => Green
[Link]([Link]); // => $3/kg
Naming Properties
Non-existent properties
const classElection = {
date: 'January 12'
};
[Link]([Link]); // undefined
[Link] 15/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
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.
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"
};
[Link](person);
/*
{
firstName: "Matilda"
age: 27
goal: "learning JavaScript"
[Link] 16/31
3/1/24, 2:01 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 [Link]
}
};
[Link]([Link]()); // => Pipey
Factory functions
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]();
const myCat = {
_name: 'Dottie',
get name() {
return this._name;
},
set name(newName) {
this._name = newName;
}
};
[Link] 18/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
# JavaScript Classes
Static Methods
class Dog {
constructor(name) {
this._name = name;
}
introduce() {
[Link]('This is ' + this._name + ' !');
}
// A static method
static bark() {
[Link]('Woof!');
}
}
Class
class Song {
constructor() {
[Link];
[Link];
}
play() {
[Link]('Song playing!');
}
}
Class Constructor
class Song {
constructor(title, artist) {
[Link] 19/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
[Link] = title;
[Link] = artist;
}
}
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];
}
}
[Link] 20/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
# 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]
[Link] 21/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
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
// [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
[Link] 22/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
}
});
Executor function
setTimeout()
setTimeout(loginAlert, 6000);
.then() method
[Link]((res) => {
[Link](res);
}, (err) => {
[Link](err);
});
.catch() method
[Link]((res) => {
[Link](value);
});
[Link] 23/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
[Link]((err) => {
[Link](err);
});
[Link]()
[Link] 24/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
Creating
[Link](res => {
return res === 'Alan' ? [Link]('Hey Alan!') : [Link]('Who are y
}).then((res) => {
[Link](res)
}, (err) => {
[Link](err)
});
[Link] 25/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
# 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);
[Link] 26/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
});
}
Error Handling
try {
let user = [Link](json); // <-- no errors
[Link]( [Link] ); // no name!
} catch (e) {
[Link]( "Invalid JSON data!" );
}
function helloWorld() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Hello World!');
}, 2000);
});
}
# JavaScript Requests
JSON
[Link] 27/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
const jsonObj = {
"name": "Rick",
"id": "11A",
"level": 4
};
XMLHttpRequest
XMLHttpRequest is a browser-level API that enables the client to script data transfers via JavaScript,
NOT part of the JavaScript language.
GET
[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] = () => {
[Link]([Link]);
};
fetch api
fetch(url, {
method: 'POST',
[Link] 28/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
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);
});
fetch('url')
.then(
response => {
[Link](response);
},
rejection => {
[Link]([Link]);
);
fetch('[Link] {
method: 'POST',
body: [Link]({id: "200"})
}).then(response => {
if([Link]){
return [Link]();
}
throw new Error('Request failed!');
}, networkError => {
[Link]([Link]);
[Link] 29/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
}).then(jsonResponse => {
[Link](jsonResponse);
})
Related Cheatsheet
Recent Cheatsheet
[Link] 30/31
3/1/24, 2:01 PM JavaScript Cheat Sheet & Quick Reference
[Link] 31/31