Javascript Cheat Sheet

August 26, 2023

A short cheat sheet for rainy days... const feedMyBrain = () => {return false}

Variables & Constants

var x = 10; // Older way to declare variables, function-scoped
let y = 20; // Modern way to declare variables, block-scoped
const z = 30; // Declare constants, block-scoped

Data Types

let str = "string";
let num = 42;
let bool = true;
let arr = [1, 2, 3];
let obj = { key: "value" };
let nul = null;
let undef = undefined;

Type Conversion

Number("10");
String(10);
Boolean(0);

Type Checking

typeof "hello";
typeof 10;

Operators

+ - * / % // Arithmetic
== === != !== // Comparison
&& || ! // Logical

Loops

for (let i = 0; i < 10; i++) {
  // code
}

while (condition) {
  // code
}

arr.forEach(function (item) {
  // code
});

for (let el of arr) {
  console.log(el)
}

Conditionals

if (condition) {
  // code
} else if (anotherCondition) {
  // code
} else {
  // code
}

let result = condition ? trueValue : falseValue;

Functions

// Function Declaration
function functionName(args) {
  // code
}

// Function Expression
const functionName = function (args) {
  // code
};

// Arrow Function aka the best kind of functions 🤓
const functionName = (args) => {
  // code
};

Objects

let obj = {
  key1: "value1",
  key2: "value2",
  method: function () {
    // code
  },
};

// Access
obj.key1;
obj["key2"];
obj.method();

Arrays

let arr = [1, 2, 3];
arr.push(4); // Add to end
arr.pop(); // Remove from end
arr.unshift(0); // Add to beginning
arr.shift(); // Remove from beginning

Arrays advanced

let nestedArray = [[1,2,3],,[1,2,3]]
for (let el of nestedArray) {
  console.log(el) // [1,2,3]
  for (let nestedEl of el) {
    console.log(nestedEl) // 1
  }
}

let array = [1,2,3]
const times2Array = array.map((value,index)=>{
  return value*2
})
console.log(times2Array) //[ 2, 4, 6 ]

Error Handling

try {
  // code that may throw an error
} catch (error) {
  // handle error
}

Promises & Async/Await

// Promise
new Promise((resolve, reject) => {
  // code
})
  .then((result) => {
    // handle result
  })
  .catch((error) => {
    // handle error
  });

// Async/Await
async function functionName() {
  try {
    let result = await someAsyncFunction();
  } catch (error) {
    // handle error
  }
}

DOM Manipulation

document.getElementById("id");
document.querySelector(".class");
document.querySelectorAll("tag");

Spread Syntax

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // {a: 1, b: 2, c: 3}

Destructuring

const [a, b, ...rest] = [1, 2, 3, 4, 5];
const { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };

Classes introduction

class MyClass {
  constructor(prop) {
    this.prop = prop;
  }

  myMethod() {
    return "Hello, world!";
  }

  static myStaticMethod() {
    return "I'm a static method";
  }
}

Classes advanced

class Person {
  #name; // private field
  #age;  // private field

  constructor(name, age) {
    this.#name = name; // Accessing a private field
    this.#age = age;   // Accessing a private field
  }

  // Public method
  introduce() {
    return `Hi, my name is ${this.#name} and I am ${this.#age} years old.`; // Accessing private fields
  }

  // Private method
  #incrementAge() {
    this.#age++; // Accessing a private field
  }

  // Public method to call a private method
  haveBirthday() {
    this.#incrementAge(); // Calling a private method
    console.log("Happy Birthday!");
  }
}

const person = new Person("Alice", 25);

console.log(person.introduce()); // "Hi, my name is Alice and I am 25 years old."

// Attempt to access private fields will result in a SyntaxError
console.log(person.#name); // SyntaxError

// Attempt to access private methods will also result in a SyntaxError
person.#incrementAge(); // SyntaxError

person.haveBirthday(); // Outputs "Happy Birthday!"

console.log(person.introduce()); // "Hi, my name is Alice and I am 26 years old."

Object deep copy

const objectCopy = (originalObject) => {
  let copiedObject = Object.assign(Object.create(Object.getPrototypeOf(originalObject)), originalObject);
  return copiedObject;
};

Template Literals

const greeting = `Hello, ${name}!`;

'this' Keyword

class TestClass {
  constructor() {
    this.value = 42;
  }

  printValue() {
    console.log(this.value);
  }
}

Async/Await with Try/Catch

async function fetchData() {
  try {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
  } catch (error) {
    console.error("Error:", error);
  }
}

Profile picture

Written by Olivier Bonnet who lives and works in Montreal writing a blog that nobody reads 🤪...

© Bonneto 2024