View All Cheat Sheets
Seiwa Holdings •
Seiwa Holdings JavaScript Basics Cheat Sheet
Essential JavaScript concepts and syntax for quick reference
javascript web-development programming
JavaScript Cheat Sheet
Basic Concepts
Variables and Declarations
// Variable declarations
let variable = 'value'; // Block-scoped, can be reassigned
const constant = 'value'; // Block-scoped, cannot be reassigned
var oldVariable = 'value'; // Function-scoped, avoid using
Primitive Data Types
let string = 'Hello world'; // String
let number = 42; // Number
let boolean = true; // Boolean
let nullValue = null; // Null
let undefinedValue; // Undefined
let symbol = Symbol('description'); // Symbol
let bigInt = 1234567890123456789012345678901234567890n; // BigInt
Reference Data Types
let array = [1, 2, 3]; // Array
let object = { key: 'value' }; // Object
let date = new Date(); // Date object
let regex = /\d+/g; // Regular expression
let map = new Map(); // Map
let set = new Set(); // Set
Functions
Function Declarations
// Function declaration
function functionName(param1, param2) {
return param1 + param2;
}
// Function expression
const functionExpression = function(param1, param2) {
return param1 + param2;
};
Arrow Functions
// Arrow function with block body
const arrowFunction = (param1, param2) => {
return param1 + param2;
};
// Arrow function with implicit return
const shortArrowFunction = (param1, param2) => param1 + param2;
// Arrow function with single parameter (parentheses optional)
const singleParam = param => param * 2;
Function Parameters
// Default parameters
function defaultParams(param1 = 'default value') {
return param1;
}
// Rest parameters
function restParams(param1, ...restOfParams) {
console.log(param1); // 'a'
console.log(restOfParams); // ['b', 'c', 'd']
}
restParams('a', 'b', 'c', 'd');
// Parameter destructuring
function destructureParams({ name, age }) {
console.log(`${name} is ${age} years old`);
}
destructureParams({ name: 'John', age: 30 });
Arrays
Array Creation and Access
// Creating arrays
let array1 = [1, 2, 3, 4, 5];
let array2 = new Array(1, 2, 3);
let filledArray = Array(5).fill(0); // [0, 0, 0, 0, 0]
// Accessing elements
array1[0]; // First element
array1[array1.length - 1]; // Last element
Array Modification Methods
// Adding and removing elements
array.push(6); // Add to end: [1, 2, 3, 4, 5, 6]
array.pop(); // Remove from end: [1, 2, 3, 4, 5]
array.unshift(0); // Add to beginning: [0, 1, 2, 3, 4, 5]
array.shift(); // Remove from beginning: [1, 2, 3, 4, 5]
// Slicing and splicing
array.slice(1, 3); // Returns [2, 3] (doesn't modify original)
array.splice(1, 2, 'a', 'b'); // Returns [2, 3], array is now [1, 'a', 'b', 4, 5]
Array Iteration Methods
// Basic iteration
array.forEach(item => console.log(item));
// Transforming arrays
array.map(item => item * 2); // Returns new array with each item doubled
// Filtering arrays
array.filter(item => typeof item === 'number'); // Returns only numbers
// Finding elements
array.find(item => item > 3); // Returns first item > 3
array.findIndex(item => item > 3); // Returns index of first item > 3
// Testing arrays
array.some(item => item > 3); // Returns true if any item > 3
array.every(item => item > 0); // Returns true if all items > 0
// Reducing arrays
array.reduce((acc, item) => acc + item, 0); // Sum of all items
Advanced Array Methods
// Flattening arrays
const nestedArray = [1, [2, 3], [4, [5, 6]]];
nestedArray.flat(); // [1, 2, 3, 4, [5, 6]]
nestedArray.flat(2); // [1, 2, 3, 4, 5, 6]
// Map and flatten in one operation
const numbers = [1, 2, 3];
numbers.flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]
// Creating arrays from array-like objects
Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
Array.from(new Set([1, 2, 2, 3])); // [1, 2, 3]
// Creating arrays with values based on index
Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]
Objects
Object Creation and Access
// Object literal
let person = {
name: 'John',
age: 30,
greet() {
return `Hello, my name is ${this.name}`;
}
};
// Accessing properties
person.name; // 'John'
person['age']; // 30
person.greet(); // 'Hello, my name is John'
Object Methods
// Object property operations
Object.keys(person); // ['name', 'age', 'greet']
Object.values(person); // ['John', 30, [Function: greet]]
Object.entries(person); // [['name', 'John'], ['age', 30], ['greet', [Function: greet]]]
// Creating objects from entries
Object.fromEntries([['name', 'Alice'], ['age', 25]]); // { name: 'Alice', age: 25 }
// Object property descriptors
Object.getOwnPropertyDescriptor(person, 'name');
Object.defineProperty(person, 'id', { value: 42, writable: false });
Object Manipulation
// Spread operator
let newPerson = { ...person, job: 'Developer' };
// Object destructuring
let { name, age } = person;
let { name: personName, age: personAge } = person; // Renaming variables
// Merging objects
Object.assign({}, obj1, obj2);
// Checking properties
'name' in person; // true
person.hasOwnProperty('name'); // true
Advanced JavaScript
Classes and Prototypes
// ES6 Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name}`;
}
static createAnonymous() {
return new Person('Anonymous', 0);
}
}
// Inheritance
class Employee extends Person {
constructor(name, age, company) {
super(name, age);
this.company = company;
}
greet() {
return `${super.greet()} and I work at ${this.company}`;
}
}
Prototypal Inheritance (Pre-ES6)
// Constructor function
function Person(name, age) {
this.name = name;
this.age = age;
}
// Adding method to prototype
Person.prototype.greet = function() {
return `Hello, my name is ${this.name}`;
};
// Creating instance
const john = new Person('John', 30);
Promises and Async/Await
// Creating a promise
const promise = new Promise((resolve, reject) => {
// Async operation
if (success) {
resolve(result);
} else {
reject(error);
}
});
// Using promises
promise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log('Operation completed'));
// Async/await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
}
}
Promise Combinators
// Run promises in parallel and wait for all to complete
Promise.all([promise1, promise2, promise3])
.then(([result1, result2, result3]) => {
// All promises fulfilled
})
.catch(error => {
// At least one promise rejected
});
// Get first fulfilled promise
Promise.race([promise1, promise2, promise3])
.then(result => {
// First promise to fulfill/reject
});
// Wait for all promises to settle
Promise.allSettled([promise1, promise2, promise3])
.then(results => {
// Array of { status: 'fulfilled'/'rejected', value/reason: ... }
});
// Get first fulfilled promise (ignores rejections)
Promise.any([promise1, promise2, promise3])
.then(result => {
// First promise to fulfill
})
.catch(errors => {
// All promises rejected
});
Modules
// Exporting
export const PI = 3.14159;
export function square(x) {
return x * x;
}
export default class Calculator { /* ... */ }
// Importing
import Calculator, { PI, square } from './math.js';
import * as math from './math.js';
import('./math.js').then(module => {
// Dynamic import
});
Generators and Iterators
// Generator function
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}
// Using a generator
const generator = numberGenerator();
console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }
// Iterating over a generator
for (const num of numberGenerator()) {
console.log(num); // 1, 2, 3
}
Proxies and Reflection
// Creating a proxy
const handler = {
get(target, prop) {
console.log(`Getting ${prop}`);
return target[prop];
},
set(target, prop, value) {
console.log(`Setting ${prop} to ${value}`);
target[prop] = value;
return true;
}
};
const proxy = new Proxy({}, handler);
proxy.name = 'John'; // Logs: Setting name to John
console.log(proxy.name); // Logs: Getting name, then 'John'
// Reflection API
Reflect.has(obj, 'property');
Reflect.get(obj, 'property');
Reflect.set(obj, 'property', value);
Reflect.deleteProperty(obj, 'property');
Web APIs
Fetch API
// Basic fetch request
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
// Fetch with options
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
body: JSON.stringify({ key: 'value' })
});
LocalStorage and SessionStorage
// LocalStorage (persists after browser close)
localStorage.setItem('key', 'value');
const value = localStorage.getItem('key');
localStorage.removeItem('key');
localStorage.clear();
// SessionStorage (cleared after browser close)
sessionStorage.setItem('key', 'value');
const sessionValue = sessionStorage.getItem('key');
DOM Manipulation
// Selecting elements
const element = document.getElementById('id');
const elements = document.querySelectorAll('.class');
// Creating and modifying elements
const newElement = document.createElement('div');
newElement.textContent = 'Hello World';
newElement.classList.add('my-class');
document.body.appendChild(newElement);
// Event handling
element.addEventListener('click', (event) => {
event.preventDefault();
console.log('Element clicked');
});
Regular Expressions
// Creating regular expressions
const regex1 = /pattern/flags;
const regex2 = new RegExp('pattern', 'flags');
// Common flags
// g - global match
// i - case-insensitive
// m - multiline
// s - dot matches newlines
// u - unicode
// y - sticky
// Testing and matching
regex.test('string'); // Returns boolean
'string'.match(regex); // Returns array of matches
'string'.replace(regex, 'replacement'); // Returns new string
Error Handling
// Try-catch block
try {
// Code that might throw an error
throw new Error('Something went wrong');
} catch (error) {
console.error('Caught an error:', error.message);
} finally {
// Always executed
console.log('Cleanup code');
}
// Custom error classes
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
// Throwing custom errors
throw new ValidationError('Invalid input');