DM
Technical reference

JavaScript Cheatsheet

A quick reference for JavaScript concepts, functions, methods, and more.

Getting Started

Console Logging

console.log("Hello world!");
console.warn("hello %s", "CheatSheets.zip");
console.error(new Error("Oops!"));

Numbers & Variables

let amount = 6;
let price = 4.99;

let x = null;
let name = "Tammy";
const found = false;

console.log(name, found, x);

var a;
console.log(a); // undefined

Strings

let single = "Wheres my bandit hat?";
console.log(single.length); // 21

Comments

// This line is a comment
/*
  Multi-line
  Comment
*/

Operators

5 + 5 // 10
10 - 5 // 5
5 * 10 // 50
10 / 5 // 2
10 % 5 // 0

Assignment Operators

let number = 100;
number = number + 10;
number += 10;
console.log(number); // 120

String Interpolation

let age = 7;
`Tommy is ${age} years old.`;

let and const

let count;
console.log(count); // undefined
count = 10;
console.log(count);

const numberOfColumns = 4;
// numberOfColumns = 8; // ❌ TypeError

Conditionals

if Statement

const isMailSent = true;
if (isMailSent) {
  console.log("Mail sent to recipient");
}

Ternary Operator

let x = 1;
const result = x == 1 ? true : false;

else if

const size = 10;
if (size > 100) {
  console.log("Big");
} else if (size > 20) {
  console.log("Medium");
} else if (size > 4) {
  console.log("Small");
} else {
  console.log("Tiny");
}

switch Statement

const food = "salad";
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");
}

Comparison & Logical Operators

1 > 3; // false
3 > 1; // true
250 >= 250; // true
1 === 1; // true
1 === "1"; // false

true || false; // true
true && true; // true
!true; // false

Nullish Coalescing (??)

null ?? "I win";       // 'I win'
undefined ?? "Me too";  // 'Me too'
false ?? "I lose";      // false
0 ?? "I lose again";    // 0

== vs ===

0 == false;        // true
0 === false;       // false
1 == "1";         // true
1 === "1";        // false
null == undefined; // true
null === undefined; // false

Functions

Function Declaration

function sum(num1, num2) {
  return num1 + num2;
}
sum(3, 6);

Anonymous & Arrow Functions

const rocketToMars = function () {
  return "BOOM!";
};

const printHello = () => {
  console.log("hello");
};

Concise Arrow Function

const multiply = (a, b) => a * b;
console.log(multiply(2, 30));

Function Expressions & Parameters

const dog = function () {
  return "Woof!";
};

function sayHello(name) {
  return `Hello, ${name}!`;
}

Scope

Block vs Function Scope

for (let i = 0; i < 3; i++) {
  // i scoped inside block
}

for (var i = 0; i < 3; i++) {
  // i accessible outside
}

Closures in Loops

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 10);
}

for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log(j), 10);
}

Arrays & Sets

Array Basics

const fruits = ["apple", "orange"];
const data = [1, "chicken", false];
fruits.length; // 2

Array Methods

fruits.push("banana");
fruits.pop();
fruits.shift();
fruits.unshift("grape");
fruits.concat(["kiwi"]);

Set Basics

const mySet = new Set([1, true, "hi"]);
mySet.add("new");
mySet.delete("hi");
mySet.has(1);

Loops

Loop Types

for (let i = 0; i < 4; i++) {}
while (i < 5) {}
do {} while (i < 5);

Loop Helpers

for...of
for...in
break;
continue;

Iterators

map / filter / reduce

array.map(fn);
array.filter(fn);
array.reduce(fn);

Callback Example

const isEven = n => n % 2 === 0;
function check(evenFunc, num) {
  console.log(evenFunc(num));
}

Objects

Basic Object Access

const apple = { color: "green" };
apple.color;

Methods, this, and Shorthand

const engine = {
  start() { console.log("go") },
  sputter: () => console.log("..."),
};

Classes & Inheritance

Class Basics

class Dog {
  constructor(name) {
    this.name = name;
  }
  bark() {
    console.log("woof");
  }
}

extends

class Media {}
class Song extends Media {}

Modules

ES Modules

export function add() {}
import { add } from './math.js';

CommonJS

module.exports = { add }
const math = require('./math.js')

Promises & Async

Promise Basics

const p = new Promise((res, rej) => {...});
p.then(...).catch(...);

Async / Await

async function load() {
  const res = await fetch(url);
}

Requests

fetch API

fetch(url, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(data)
})

XHR

const xhr = new XMLHttpRequest();
xhr.open("GET", "/path");
xhr.send();