Site icon CloudCusp

JavaScript CheatSheet Table with Example: 40+ Essential JS Features Explained

JavaScript cheatsheet

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

JavaScript CheatSheet

FeatureSyntax/ExampleExplanationNotes
Declare Variableslet x = 10;
const y = 20;
Use let for reassignable variables and const for constantsAvoid using var due to scoping issues
Data Typesstring, number, boolean, objectJavaScript supports primitive and reference typesUse typeof to check data types
Template Literals`Hello, ${name}`Embed expressions in stringsUse backticks for multi-line strings
Functionsfunction name(params) { ... }Define reusable blocks of codeArrow functions: const fn = () => { ... }
Arrow Functionsconst add = (a, b) => a + b;Shorter syntax for anonymous functionsNo this binding
Array Methods.push(), .pop(), .map(), .filter()Built-in methods for working with arraysCommonly used for transforming and manipulating arrays
String Methods.length, .slice(), .replace()Built-in methods for string operationsStrings are immutable; methods return new strings
Object Destructuringconst {a, b} = obj;Extract properties from objectsWorks with arrays too: const [x, y] = arr;
Spread Operatorconst newArr = [...arr1, ...arr2];Expands arrays or objects into individual elementsUseful for merging arrays or objects
Rest Operatorfunction sum(...nums) { }Collects arguments into an arrayOpposite of the spread operator
Conditional Statementsif (x > 5) { } else { }Used for decision-makingTernary: condition ? value1 : value2;
Switch Statementswitch (key) { case 1: ... }Simplifies multiple conditional checksUse default for unmatched cases
Loopsfor, while, do...whileIterates over arrays, objects, or numbersUse for...of for arrays and for...in for objects
Event Listenerselement.addEventListener('click', fn);Attaches an event handler to an elementUse removeEventListener to clean up
Promisesnew Promise((resolve, reject) => { });Handles asynchronous operations.then() and .catch() for chaining
Async/Awaitasync function fn() { await promise; }Syntactic sugar for promisesRequires async keyword
Error Handlingtry { ... } catch (err) { ... }Catches runtime errorsUse finally for cleanup operations
DOM Manipulationdocument.querySelector('.class');Access and modify HTML elementsUse .innerHTML or .textContent to update content
Event Delegationparent.addEventListener('click', fn);Use a parent element to handle events for multiple child elementsImproves performance when dealing with dynamic elements
TimerssetTimeout(fn, ms);
setInterval()
Delays or repeats executionUse clearTimeout and clearInterval to stop them
Modulesexport const x;
import { x } from
Reuse code across filesUse default export for single-value exports
Classesclass MyClass { constructor() { } }Blueprint for creating objectsUse extends for inheritance
Fetch APIfetch(url).then(res => res.json());Makes HTTP requestsSupports modern promise-based syntax
LocalStoragelocalStorage.setItem('key', value);Stores key-value pairs persistentlyUse sessionStorage for temporary storage
Object MethodsObject.keys(obj), Object.values(obj)Retrieves keys, values, or entries from an objectIterates objects effectively
Map and Setnew Map(), new Set()Efficient data structures for key-value pairs and unique valuesUse .has() and .add() for checks and additions
Regular Expressions/pattern/.test(string)Matches patterns in stringsUse exec() for detailed match results
Short-Circuiting`const x = ab;<br>a && b;`
Nullish Coalescingconst x = a ?? b;Returns right operand if left is null or undefinedMore precise than `
Debouncingconst fn = debounce(func, delay);Limits frequency of a function executionUseful for optimizing event handlers
Throttlingconst fn = throttle(func, delay);Ensures a function runs at most once per specified intervalOften used in scroll or resize events
Event LoopExplains how JS handles async operationsJS uses a single-threaded model with non-blocking asynchronous APIsLearn tasks, microtasks, and priorities
Arrow Function + ThisNo binding of this in arrow functionsRetains this from enclosing contextUseful in callbacks
Optional Chainingobj?.prop?.nestedPropSafely accesses nested propertiesAvoids runtime errors on null or undefined
Dynamic Importsimport('./module.js').then(module => { });Lazily load modulesUseful for performance optimization
Optional Parametersfunction fn(a, b = 10) { }Allows setting default values for function parametersProvides flexibility in function calls
SetTimeout with ArgumentssetTimeout(fn, ms, arg1, arg2)Passes additional arguments to the callback functionUseful for dynamic time-based executions
GlobalThisglobalThis.propertyA standardized way to access the global objectWorks across environments (browser, Node.js, etc.)
Intl APInew Intl.NumberFormat().format(num)Formats numbers, dates, and strings for internationalizationUse Intl.DateTimeFormat for date localization
WeakMap and WeakSetnew WeakMap(), new WeakSet()Holds objects without preventing garbage collectionIdeal for private properties and memory optimization
Symbol Data Typeconst sym = Symbol('desc');Creates unique and immutable valuesUsed for creating custom object properties
Proxy Objectnew Proxy(target, handler)Intercepts and customizes operations on objectsUseful for validation, logging, or data binding
BigIntconst big = 123n;Represents integers with arbitrary precisionUse BigInt for calculations beyond Number.MAX_SAFE_INTEGER
Dynamic Property Keysconst obj = { [keyName]: value };Creates object keys dynamicallyEnables 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.

Exit mobile version