JavaScript is a cornerstone of modern web development, offering the flexibility to create dynamic and interactive user experiences. Mastering JavaScript can be daunting, given its wide range of features and capabilities. That’s why we’ve created this comprehensive javascript cheatsheet to cover everything you need—from basic syntax to advanced concepts.
Whether you’re a beginner or an experienced developer, this JS cheatsheet is designed to provide quick reference and actionable insights.
On This Page
Table of Contents
JavaScript CheatSheet
Feature
Syntax/Example
Explanation
Notes
Declare Variables
let x = 10; const y = 20;
Use let for reassignable variables and const for constants
Avoid using var due to scoping issues
Data Types
string, number, boolean, object
JavaScript supports primitive and reference types
Use typeof to check data types
Template Literals
`Hello, ${name}`
Embed expressions in strings
Use backticks for multi-line strings
Functions
function name(params) { ... }
Define reusable blocks of code
Arrow functions: const fn = () => { ... }
Arrow Functions
const add = (a, b) => a + b;
Shorter syntax for anonymous functions
No this binding
Array Methods
.push(), .pop(), .map(), .filter()
Built-in methods for working with arrays
Commonly used for transforming and manipulating arrays
String Methods
.length, .slice(), .replace()
Built-in methods for string operations
Strings are immutable; methods return new strings
Object Destructuring
const {a, b} = obj;
Extract properties from objects
Works with arrays too: const [x, y] = arr;
Spread Operator
const newArr = [...arr1, ...arr2];
Expands arrays or objects into individual elements
Useful for merging arrays or objects
Rest Operator
function sum(...nums) { }
Collects arguments into an array
Opposite of the spread operator
Conditional Statements
if (x > 5) { } else { }
Used for decision-making
Ternary: condition ? value1 : value2;
Switch Statement
switch (key) { case 1: ... }
Simplifies multiple conditional checks
Use default for unmatched cases
Loops
for, while, do...while
Iterates over arrays, objects, or numbers
Use for...of for arrays and for...in for objects
Event Listeners
element.addEventListener('click', fn);
Attaches an event handler to an element
Use removeEventListener to clean up
Promises
new Promise((resolve, reject) => { });
Handles asynchronous operations
.then() and .catch() for chaining
Async/Await
async function fn() { await promise; }
Syntactic sugar for promises
Requires async keyword
Error Handling
try { ... } catch (err) { ... }
Catches runtime errors
Use finally for cleanup operations
DOM Manipulation
document.querySelector('.class');
Access and modify HTML elements
Use .innerHTML or .textContent to update content
Event Delegation
parent.addEventListener('click', fn);
Use a parent element to handle events for multiple child elements
Improves performance when dealing with dynamic elements
Timers
setTimeout(fn, ms); setInterval()
Delays or repeats execution
Use clearTimeout and clearInterval to stop them
Modules
export const x; import { x } from
Reuse code across files
Use default export for single-value exports
Classes
class MyClass { constructor() { } }
Blueprint for creating objects
Use extends for inheritance
Fetch API
fetch(url).then(res => res.json());
Makes HTTP requests
Supports modern promise-based syntax
LocalStorage
localStorage.setItem('key', value);
Stores key-value pairs persistently
Use sessionStorage for temporary storage
Object Methods
Object.keys(obj), Object.values(obj)
Retrieves keys, values, or entries from an object
Iterates objects effectively
Map and Set
new Map(), new Set()
Efficient data structures for key-value pairs and unique values
Use .has() and .add() for checks and additions
Regular Expressions
/pattern/.test(string)
Matches patterns in strings
Use exec() for detailed match results
Short-Circuiting
`const x = a
b;<br>a && b;`
Nullish Coalescing
const x = a ?? b;
Returns right operand if left is null or undefined
More precise than `
Debouncing
const fn = debounce(func, delay);
Limits frequency of a function execution
Useful for optimizing event handlers
Throttling
const fn = throttle(func, delay);
Ensures a function runs at most once per specified interval
Often used in scroll or resize events
Event Loop
Explains how JS handles async operations
JS uses a single-threaded model with non-blocking asynchronous APIs
Learn tasks, microtasks, and priorities
Arrow Function + This
No binding of this in arrow functions
Retains this from enclosing context
Useful in callbacks
Optional Chaining
obj?.prop?.nestedProp
Safely accesses nested properties
Avoids runtime errors on null or undefined
Dynamic Imports
import('./module.js').then(module => { });
Lazily load modules
Useful for performance optimization
Optional Parameters
function fn(a, b = 10) { }
Allows setting default values for function parameters
Provides flexibility in function calls
SetTimeout with Arguments
setTimeout(fn, ms, arg1, arg2)
Passes additional arguments to the callback function
Useful for dynamic time-based executions
GlobalThis
globalThis.property
A standardized way to access the global object
Works across environments (browser, Node.js, etc.)
Intl API
new Intl.NumberFormat().format(num)
Formats numbers, dates, and strings for internationalization
Use Intl.DateTimeFormat for date localization
WeakMap and WeakSet
new WeakMap(), new WeakSet()
Holds objects without preventing garbage collection
Ideal for private properties and memory optimization
Symbol Data Type
const sym = Symbol('desc');
Creates unique and immutable values
Used for creating custom object properties
Proxy Object
new Proxy(target, handler)
Intercepts and customizes operations on objects
Useful for validation, logging, or data binding
BigInt
const big = 123n;
Represents integers with arbitrary precision
Use BigInt for calculations beyond Number.MAX_SAFE_INTEGER
Dynamic Property Keys
const obj = { [keyName]: value };
Creates object keys dynamically
Enables flexibility in object creation
FAQs
Why is JavaScript important for developers?
JavaScript is a versatile, client-side language that powers interactive web applications. It is crucial for front-end, back-end, and even mobile development.
What are some advanced features included in the cheat sheet?
Features like Promises, Async/Await, Proxy Objects, WeakMap, Symbols, and the Intl API are considered advanced and are covered in the cheat sheet.
Can I use this cheat sheet for ES6+ JavaScript?
Yes, the cheat sheet includes modern JavaScript features introduced in ES6 and later versions, like template literals, arrow functions, and the spread operator.
What are some commonly used array methods in JavaScript?
Methods like .map(), .filter(), .reduce(), .push(), and .pop() are commonly used to manipulate and transform arrays.
Is JavaScript only used for front-end development?
No, JavaScript is also used for back-end development with frameworks like Node.js and for building mobile applications with tools like React Native.
How can I format numbers or dates in JavaScript?
You can use the Intl.NumberFormat and Intl.DateTimeFormat APIs to format numbers and dates for different locales.
Are there any features to handle asynchronous tasks in JavaScript?
Yes, JavaScript provides Promises, Async/Await, and the Fetch API for handling asynchronous tasks effectively.
+ There are no comments
Add yours