JavaScript Cheatsheet for fast paced web developers and product managers
Basics:
Variables and Data Types:
let variableName = 'value'; // String
const constantValue = 42; // Integer
Operators:
let sum = 5 + 3;
let product = 10 * 2;
Conditionals:
if (condition) {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}
Loops:
for (let i = 0; i < 5; i++) {
// code to repeat
}
Functions:
Function Declaration:
function add(a, b) {
return a + b;
}
Arrow Functions:
const multiply = (x, y) => x * y;
Callback Functions:
function fetchData(callback) {
// asynchronous operation
callback(data);
}
Arrays and Objects:
Arrays:
const fruits = ['apple', 'banana', 'orange'];
fruits.push('grape'); // add element
Objects:
const person = {
name: 'John',
age: 30,
};
DOM Manipulation:
Selecting Elements:
const element = document.getElementById('myElement');
Event Handling:
element.addEventListener('click', () => {
// code to execute on click
});
Asynchronous JavaScript:
Promises:
const fetchData = () => {
return new Promise((resolve, reject) => {
// asynchronous operation
if (success) {
resolve(data);
} else {
reject('Error!');
}
});
};
Async/Await:
const fetchData = async () => {
try {
const result = await fetchData();
console.log(result);
} catch (error) {
console.error(error);
}
};
ES6+ Features:
Destructuring:
const { name, age } = person;
Template Literals:
const greeting = `Hello, ${name}!`;
Spread Operator:
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4];
Classes:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
Advanced Functions:
Higher-Order Functions:
const multiplyBy = (factor) => (number) => number * factor;
const double = multiplyBy(2);
Closures:
function outerFunction() {
let outerVar = 'I am outer!';
function innerFunction() {
console.log(outerVar);
}
return innerFunction;
}
Advanced Array Operations:
Map and Filter:
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
const evens = numbers.filter(num => num % 2 === 0);
Reduce:
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
ES6+ Features (Continued):
Object Destructuring:
const { name, age, address: { city } } = person;
Default Parameters:
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
Asynchronous JavaScript (Continued):
Fetch API:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Promise.all:
const fetchData1 = fetch('https://api.example.com/data1');
const fetchData2 = fetch('https://api.example.com/data2');
Promise.all([fetchData1, fetchData2])
.then(responses => Promise.all(responses.map(response => response.json())))
.then(data => console.log(data))
.catch(error => console.error(error));
Modern JavaScript:
Optional Chaining:
const city = person?.address?.city;
Nullish Coalescing Operator:
const username = getUser()?.username ?? 'Guest';
Advanced JavaScript Concepts:
Generators:
function* generatorFunction() {
yield 'Step 1';
yield 'Step 2';
yield 'Step 3';
}
const generator = generatorFunction();
Async/Await:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
Functional Programming:
Currying:
const curryAdd = (a) => (b) => (c) => a + b + c;
const addNumbers = curryAdd(1)(2);
const result = addNumbers(3);
Memoization:
const memoize = (fn) => {
const cache = new Map();
return (...args) => {
const key = args.join('-');
return cache.has(key) ? cache.get(key) : cache.set(key, fn(...args)).get(key);
};
};
Design Patterns:
Singleton Pattern:
class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
}
Observer Pattern:
class Subject {
constructor() {
this.observers = [];
}
addObserver(observer) {
this.observers.push(observer);
}
notify(message) {
this.observers.forEach(observer => observer.update(message));
}
}
Browser API:
Local Storage:
localStorage.setItem('key', 'value');
const storedValue = localStorage.getItem('key');
Geolocation:
navigator.geolocation.getCurrentPosition(
position => console.log(position.coords),
error => console.error(error)
);
Miscellaneous:
Regular Expressions:
const pattern = /^[A-Za-z]+$/;
const isValid = pattern.test('Hello');
Module Exports:
// math.js
export const add = (a, b) => a + b;
// main.js
import { add } from './math.js';