[Go to site: main page, start]

0% found this document useful (0 votes)
1K views9 pages

JavaScript Ultimate Cheat Sheet

The document provides a comprehensive cheat sheet for JavaScript, summarizing key data types, variables, operators, control flow, functions, arrays, objects, strings, promises, modules, error handling, DOM manipulation, AJAX/Fetch API, storage, APIs, testing, patterns, libraries, frameworks, and resources. It covers the fundamentals of JavaScript as well as more advanced topics like promises, async/await, classes, modules, and design patterns. Sections are formatted with descriptive emojis and cover syntax, methods, and best practices.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views9 pages

JavaScript Ultimate Cheat Sheet

The document provides a comprehensive cheat sheet for JavaScript, summarizing key data types, variables, operators, control flow, functions, arrays, objects, strings, promises, modules, error handling, DOM manipulation, AJAX/Fetch API, storage, APIs, testing, patterns, libraries, frameworks, and resources. It covers the fundamentals of JavaScript as well as more advanced topics like promises, async/await, classes, modules, and design patterns. Sections are formatted with descriptive emojis and cover syntax, methods, and best practices.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Data Types and Variables
  • Functions and Arrays
  • Objects and Strings
  • Modules and Error Handling
  • AJAX, Local Storage, Web APIs
  • Debugging Tools and Testing
  • ES6+ and Frameworks
  • Resources

#_ the JavaScript Ultimate CheatSheet

💠 Data Types
┣ 📋 `Number` : Represents numeric values (integers and floats).
┣ 📋 `String` : Represents textual data.
┣ 📋 `Boolean` : Represents true or false values.
┣ 📋 `Null` : Represents the intentional absence of any object
value.
┣ 📋 `Undefined` : Represents a variable that has been declared but
has not been assigned a value.
┗ 📋 `Object` : Represents a collection of key-value pairs.

💠 Variables & Constants


┣ 📦 `var` : Function-scoped variable declaration (ES5).
┣ 📦 `let` : Block-scoped variable declaration (ES6).
┣ 📦 `const` : Block-scoped constant declaration (ES6).

💠 Operators
┣ ➕ `Arithmetic` : +, -, *, /, % (remainder).
┣ 📈 `Assignment` : =, +=, -=, *=, /=, %=
┣ 🔄 `Increment/Decrement` : ++, --
┣ ⚖️ `Comparison` : ==, ===, !=, !==, <, >, <=, >=
┣ ⚛️ `Logical` : && (AND), || (OR), ! (NOT)
┣ 🌟 `Ternary` : condition ? expr1 : expr2

💠 Control Flow
┣ 🔄 `if` : Executes a statement if a condition is true.
┣ 🔄 `else` : Executes a statement if the 'if' condition is false.
┣ 🔄 `else if` : Executes a statement if another 'if' condition is
true.
┣ 🔁 `for` : Loops through a block of code a specified number of
times.

By: Waleed Mousa


┣ 🔁 `while` : Loops through a block of code while a condition is
true.
┣ 🔁 `do...while` : Loops through a block of code at least once
before checking the condition.
┗ ⏹️ `switch` : Selects one of many blocks of code to be executed.

💠 Functions
┣ 📑 `Function Declaration` : function functionName(parameters) {
... }
┣ 📑 `Function Expression` : const functionName =
function(parameters) { ... }
┣ 📑 `Arrow Function` : (parameters) => { ... }
┣ 📑 `Default Parameters` : function functionName(param =
defaultValue) { ... }
┣ 📑 `Rest Parameters` : function functionName(...args) { ... }
┣ 📑 `Immediately Invoked Function Expression (IIFE)` : (function()
{ ... })()
┗ 📑 `Higher-Order Functions` : Functions that take other functions
as arguments or return functions.

💠 Arrays
┣ 📚 `Creation` : const arr = [elem1, elem2, ...];
┣ 📚 `Accessing Elements` : arr[index]
┣ 📚 `Adding Elements` : [Link](elem), [Link](elem)
┣ 📚 `Removing Elements` : [Link](), [Link]()
┣ 📚 `Slicing` : [Link](startIndex, endIndex)
┣ 📚 `Spreading` : const newArray = [...arr]
┣ 📚 `Iterating` : [Link](callback), [Link](callback),
[Link](callback)
┗ 📚 `Reducing` : [Link](callback, initialValue)

By: Waleed Mousa


💠 Objects
┣ 🔑 `Creating Objects` : const obj = { key: value, ... }
┣ 🔑 `Accessing Properties` : [Link] or obj['key']
┣ 🔑 `Adding Properties` : [Link] = value
┣ 🔑 `Deleting Properties` : delete [Link]
┣ 🔑 `Object Methods` : Methods defined within an object.
┣ 🔑 `Object Destructuring` : const { key1, key2 } = obj;
┗ 🔑 `Object Spread` : const newObj = { ...obj, newKey: newValue }

💠 Strings
┣ 📝 `Length` : [Link]
┣ 📝 `Indexing` : str[index]
┣ 📝 `Substring` : [Link](startIndex, endIndex)
┣ 📝 `Split` : [Link](separator)
┣ 📝 `Trim` : [Link]()
┣ 📝 `Concatenate` : [Link](str1, str2, ...)
┗ 📝 `Template Literal` : `Hello, ${name}!`

💠 Promises & Async/Await


┣ ⏳ `Callbacks` : A function passed as an argument to another
function to be executed later.
┣ ⏳ `Callback Hell` : Nested and unreadable code due to excessive
use of callbacks.
┣ 🚀 `Promise` : An object representing the eventual completion or
failure of an asynchronous operation.
┣ 🚀 `Promise States` : Pending, Fulfilled, Rejected
┣ 🚀 `Promise Methods` : .then(), .catch(), .finally()
┣ ⏳ `Chaining Promises` : Using .then() to chain multiple
asynchronous operations.
┣ ⏳ `[Link]` : Resolves an array of promises and returns a
new promise that resolves to an array of resolved values.
┣ ⏳ `[Link]` : Resolves or rejects as soon as one of the
promises in an iterable resolves or rejects.

By: Waleed Mousa


┣ 🚀 `Async/Await` : A syntax to write asynchronous code that looks
like synchronous code.
┣ ⏳ `try...catch with Async/Await` : Handling errors in
asynchronous code.
┗ 🚀 `Async Function` : An asynchronous function that always
returns a Promise.

💠 Modules & Imports


┣ 📦 `Module Exports` : export const funcName = () => { ... }
┣ 📦 `Named Exports` : export { func1, func2 }
┣ 📦 `Default Exports` : export default funcName
┣ 📦 `Importing Modules` : import { funcName } from './[Link]'
┗ 📦 `Importing Default` : import funcName from './[Link]'

💠 Error Handling
┣ 🔍 `try...catch` : Catches errors in a block of code.
┣ 🔍 `throw` : Throws a custom error.
┗ 🔍 `Error Object` : new Error('Error message')

💠 Event Handling
┣ 🎉 `addEventListener` : Attaches an event handler to an element.
┣ 🎉 `Event Object` : Contains information about the event.
┣ 🎉 `Event Propagation` : Bubbling & Capturing.
┗ 🎉 `Preventing Default` : [Link]()

💠 DOM Manipulation
┣ 🖌️ `getElementById` : Retrieves an element by its id.
┣ 🖌️ `getElementsByClassName` : Retrieves elements by their class
name.
┣ 🖌️ `getElementsByTagName` : Retrieves elements by their tag name.

By: Waleed Mousa


┣ 🖌️ `querySelector` : Retrieves the first element that matches a
specified CSS selector.
┣ 🖌️ `querySelectorAll` : Retrieves all elements that match a
specified CSS selector.
┗ 🖌️ `Creating Elements` : [Link](tagName)

💠 AJAX & Fetch API


┣ 🌐 `XMLHttpRequest` : Making asynchronous HTTP requests.
┣ 🌐 `Fetch API` : A modern alternative to XMLHttpRequest for
making network requests.
┗ 🌐 `Async/Await with Fetch` : Making asynchronous network
requests with fetch.

💠 Local Storage
┣ 💾 `setItem` : Stores data in local storage.
┣ 💾 `getItem` : Retrieves data from local storage.
┗ 💾 `removeItem` : Removes data from local storage.

💠 Web APIs
┣ 🌍 `Geolocation API` : Retrieves the user's geographic location.
┣ 🌍 `Notification API` : Displays desktop notifications.
┣ 🌍 `Canvas API` : Draws graphics on a web page.
┣ 🌍 `Audio & Video API` : Controls audio and video playback.
┣ 🌍 `WebSockets API` : Enables real-time communication between
clients and servers.
┗ 🌍 `Service Workers` : Enables progressive web app features like
offline support.

By: Waleed Mousa


💠 Error & Debugging Tools
┣ 🐞 `[Link]` : Outputs a message to the console.
┣ 🐞 `[Link]` : Outputs a warning message to the console.
┣ 🐞 `[Link]` : Outputs an error message to the console.
┣ 🐞 `debugger` : Pauses the execution of code and opens the
browser's debugger.
┗ 🐞 `DevTools` : Browser developer tools for inspecting and
debugging.

💠 Regular Expressions (Regex)


┣ 🔍 `Creation` : const regex = /pattern/modifiers;
┣ 🔍 `Test` : [Link](str)
┣ 🔍 `Match` : [Link](regex)
┣ 🔍 `Modifiers` : g (global), i (case-insensitive), m (multiline)
┣ 🔍 `Character Classes` : \d (digit), \w (word), \s (whitespace),
...
┣ 🔍 `Quantifiers` : + (one or more), * (zero or more), ? (zero or
one), {n} (exactly n times), {n,} (n or more), {n,m} (between n and m
times)
┗ 🔍 `Groups and Capturing` : (group), (?:non-capturing group),
/(pattern)/ (capturing group)

💠 Unit Testing
┣ 🧪 `Jest` : A popular JavaScript testing framework.
┣ 🧪 `describe` : Groups test cases.
┣ 🧪 `it` : Defines a test case.
┣ 🧪 `expect` : Defines assertions for test validation.
┗ 🧪 `mock` : Creates mock functions and modules for testing.

By: Waleed Mousa


💠 ES6+ Features
┣ 🌟 `Destructuring` : const { key } = obj;
┣ 🌟 `Spread Operator` : const newArray = [...arr];
┣ 🌟 `Rest Parameters` : function functionName(...args) { ... }
┣ 🌟 `Arrow Functions` : (parameters) => { ... }
┣ 🌟 `Classes` : class ClassName { ... }
┗ 🌟 `Modules` : export, import

💠 Web Development Libraries & Frameworks


┣ 🧱 `[Link]` : A JavaScript library for building user
interfaces.
┣ 🧱 `Angular` : A TypeScript-based web application framework.
┣ 🧱 `[Link]` : A progressive JavaScript framework for building
user interfaces.
┗ 🧱 `jQuery` : A fast, small, and feature-rich JavaScript library.

💠 JavaScript Design Patterns


┣ 🧩 `Singleton` : Ensures only one instance of a class is created
and provides a global point of access to it.
┣ 🧩 `Observer` : Allows an object to publish changes to its state
to other objects.
┣ 🧩 `Factory` : Creates objects without specifying the exact class
of the object that will be created.
┣ 🧩 `Decorator` : Dynamically adds behavior to objects at runtime.
┣ 🧩 `Adapter` : Converts the interface of a class into another
interface that clients expect.
┣ 🧩 `Facade` : Provides a unified interface to a set of interfaces
in a subsystem.
┗ 🧩 `Command` : Encapsulates a request as an object, allowing for
parameterization of clients with different requests, queuing of
requests, and logging of the requests.

By: Waleed Mousa


💠 Resources
┣ 📖 `MDN Web Docs` : Official Mozilla Developer Network JavaScript
documentation.
┣ 📖 `w3schools` : Online tutorials and reference materials for web
development.
┣ 📖 `[Link]` : Modern JavaScript tutorials and reference.
┣ 📖 `Eloquent JavaScript` : A comprehensive JavaScript book by
Marijn Haverbeke.
┣ 📺 Traversy Media : Comprehensive web development tutorials by
Brad Traversy. (Link: [Link]
┣ 📺 The Net Ninja : Web development tutorials with a focus on
JavaScript and frameworks. (Link:
[Link]
┣ 📺 [Link] : Covers a wide range of topics, including
JavaScript and frontend development. (Link:
[Link]
┣ 📺 Fireship : Short and to-the-point JavaScript tips and tricks.
(Link: [Link]
┣ 📺 Programming with Mosh : Practical JavaScript and web
development tutorials. (Link:
[Link]
┣ 📺 Academind : Web development tutorials, including JavaScript
and frameworks. (Link: [Link]
┣ 📺 The Coding Train : Creative coding tutorials, including
JavaScript and [Link]. (Link: [Link]
┣ 📺 LevelUpTuts : Covers various frontend technologies, including
JavaScript. (Link: [Link]
┗ 📺 Codevolution : JavaScript and frontend development tutorials.
(Link: [Link]

By: Waleed Mousa


By: Waleed Mousa

Common questions

Powered by AI

Closures in JavaScript are functions that have access to the outer (enclosing) function’s variables—their own scope, the scope chain—when the function is nested inside another function. Variables declared with 'var' inside a function are function-scoped, so they’re accessible throughout the entire enclosing function. However, 'let' and 'const' are block-scoped, meaning that they are only accessible within the block they are defined in (such as inside an if-statement or for a loop). When closures capture variables, 'var' variables are captured by value due to hoisting before execution while 'let' and 'const' are block-sensitive and respect the time they were declared .

Higher-order functions in JavaScript are functions that can take other functions as arguments or return them as results. They enable functional programming patterns by allowing operations like function composition, transformation, and reusable, abstraction-oriented code writing. Examples include functions like .map(), .filter(), and .reduce() which can transform arrays based on given rules. For example, using .map() allows applying a transformation function to every element in an array, returning a new array with transformed values .

The 'Factory' design pattern in JavaScript is a creational pattern used to create objects in a way that abstractly separates the instantiation process. For example, it can be implemented to produce different types of objects based on given parameters, without exposing the creation logic to the client. This pattern is also used to deal with complex objects and enhances scalability and maintainability. A 'Factory' might be implemented as a method that determines which specific class of objects to instantiate and return, allowing dynamic object creation without coupling to specific classes .

A developer might choose `splice` over `slice` when they need to remove or replace existing elements in an array, as `splice` modifies the original array. It can add or exclude elements from the specified position, useful for scenarios requiring in-place modifications. In contrast, `slice` creates a new array based on a subset of an original array, without affecting the source. Thus, `splice` is chosen for mutations while `slice` is used for creating copies .

The Singleton pattern is appropriate when a class must have a single instance and that instance is needed throughout different parts of an application, like managing a global application state or caching. The Observer pattern is suitable for scenarios where objects need to automatically react to changes in another object, such as updating user interface elements when data models change in real time applications, similar to event listeners or pub-sub mechanisms .

Async/await syntax simplifies error handling in asynchronous operations by integrating the use of try...catch blocks that manage exceptions, much like synchronous try-catch expressions. This integration streamlines error management, removing the need for then().catch() chains typical of promises. As a result, code structure becomes cleaner and easier to read, aiding in tracking logic flow and handling potential errors .

The Fetch API provides a more powerful and flexible feature set for making HTTP requests compared to XMLHttpRequest. It offers a more straightforward and promise-based syntax, eliminating the need for callback functions required by XMLHttpRequest, resulting in more readable asynchronous code. Fetch also introduces features like streaming of requests and responses, a simpler interface for setting up requests with methods like GET, POST, and using headers more conveniently. However, Fetch is not backward compatible with older browsers without polyfills .

Template literals in ES6 enhance string operations by not only allowing more readable and concise syntax with embedded expressions using the `${...}` syntax but also supporting multi-line strings without requiring escape characters for newlines. This feature reduces mistakes common in building complex strings with the `+` operator which requires more verbose and error-prone construction. Template literals facilitate embedding expressions directly in strings and improve code readability and maintenance .

Array destructuring in ES6 allows more concise syntax when extracting data from arrays, improving readability, and making code more expressive especially in variable assignments. It simplifies the process of pulling values out of arrays by unbundling specific values into easily manageable variables. However, a potential pitfall is that if carelessly used, it can lead to unreadability if elements are deeply nested, or cause mismatches if the array does not contain all required elements, potentially leading to 'undefined' variable values .

Promise chaining in JavaScript involves structuring asynchronous operations in a flat, readable sequence using .then() and .catch() methods, which can make error handling more cumbersome and affect readability if chains become too lengthy. Conversely, async/await syntax simplifies error handling by using try...catch blocks and flattens the structure of asynchronous operations into a synchronous-looking style, improving readability and making the code easier to reason about .

#_ the JavaScript Ultimate CheatSheet
💠Data Types
┣📋`Number` : Represents numeric values (integers and floats).
┣📋`String`
┣🔁`while` : Loops through a block of code while a condition is
true.
┣🔁`do...while` : Loops through a block of code at leas
💠Objects
┣🔑`Creating Objects` : const obj = { key: value, ... }
┣🔑`Accessing Properties` : obj.key or obj['key']
┣🔑`Addin
┣🚀`Async/Await` : A syntax to write asynchronous code that looks
like synchronous code.
┣⏳`try...catch with Async/Await` : H
┣🖌️`querySelector` : Retrieves the first element that matches a
specified CSS selector.
┣🖌️`querySelectorAll` : Retrieves a
💠Error & Debugging Tools
┣🐞`console.log` : Outputs a message to the console.
┣🐞`console.warn` : Outputs a warning message
💠ES6+ Features
┣🌟`Destructuring` : const { key } = obj;
┣🌟`Spread Operator` : const newArray = [...arr];
┣🌟`Rest Paramete
💠Resources
┣📖`MDN Web Docs` : Official Mozilla Developer Network JavaScript
documentation.
┣📖`w3schools` : Online tutorial
By: Waleed Mousa

You might also like