javascript

JavaScript Cheatsheet All in one

1. JavaScript Array Methods Cheat Sheet

forEach(): Executes a provided function once for each array element.

array.forEach(callback);

map(): Creates a new array by applying a function to each element.

const newArray = array.map(callback);

filter(): Creates a new array with elements that pass the test.

const newArray = array.filter(callback);

reduce(): Reduces an array to a single value.

const result = array.reduce(callback, initialValue);

some(): Tests if at least one element passes the test.

const hasEven = array.some(callback);

every(): Tests if all elements pass the test.

const allEven = array.every(callback);

find(): Returns the first element that satisfies a condition.

const found = array.find(callback);

findIndex(): Returns the index of the first element that satisfies a condition.

const index = array.findIndex(callback);

includes(): Checks if an array includes a certain value.

const exists = array.includes(value);

sort(): Sorts the array in place.

array.sort(compareFunction);

reverse(): Reverses the array in place.

array.reverse();

splice(): Changes the contents of an array by removing or replacing existing elements and/or adding new elements.

array.splice(start, deleteCount, item1, item2, ...);

slice(): Returns a shallow copy of a portion of an array.

const newArray = array.slice(start, end);

flat(): Flattens a nested array.

const nestedArray = [1, [2, 3], [4, [5]]];
const flatArray = nestedArray.flat(2); // [1, 2, 3, 4, 5]

flatMap(): Maps each element using a mapping function and flattens the result.

const array = [1, 2, 3];
const result = array.flatMap(x => [x * 2]); // [2, 4, 6]

join(): Joins all elements of an array into a string.

const array = ['Hello', 'World'];
const string = array.join(' '); // "Hello World"

fill(): Fills all elements in an array with a static value.

const array = new Array(5).fill(0); // [0, 0, 0, 0, 0]

copyWithin(): Shallow copies part of an array to another location.

const array = [1, 2, 3, 4, 5];
array.copyWithin(0, 3); // [4, 5, 3, 4, 5]

2. JavaScript Objects Cheat Sheet

Creating Objects:

const person = {
    name: "Alice",
    age: 25,
    greet: function() {
        console.log("Hello, " + this.name);
    }
};

Object Creation:

const car = new Object(); // Using Object constructor
car.make = "Toyota";
car.model = "Corolla";

Object.keys(): Returns an array of a given object’s property names.

const keys = Object.keys(car); // ["make", "model"]

Object.values(): Returns an array of a given object’s property values.

const values = Object.values(car); // ["Toyota", "Corolla"]

Object.entries(): Returns an array of a given object’s key-value pairs.

const entries = Object.entries(car); // [["make", "Toyota"], ["model", "Corolla"]]

Object.assign(): Copies all enumerable own properties from one or more source objects to a target object.

const target = { a: 1 };
const source = { b: 2 };
Object.assign(target, source); // { a: 1, b: 2 }

Accessing Properties:

console.log(person.name); // Alice
person.greet(); // Hello, Alice

Destructuring:

const { name, age } = person;
console.log(name); // Alice

Adding/Updating Properties:

person.city = "New York"; // Add property
person.age = 26; // Update property

Deleting Properties:

delete person.age; // Remove property

Checking Property Existence:

console.log("name" in person); // true

3. JavaScript Functions Cheat Sheet

Function Declaration:

function add(x, y) {
    return x + y;
}

Function Expression:

const multiply = function (x, y) {
    return x * y;
};

Arrow Functions:

const divide = (x, y) => x / y;

Higher-Order Functions:

const numbers = [1, 2, 3];
const squares = numbers.map(num => num ** 2);

Immediately Invoked Function Expression (IIFE):

(function() {
    console.log("IIFE executed!");
})();

Callback Functions:

function greeting(name, callback) {
    console.log("Hello, " + name);
    callback();
}

greeting("Alice", () => {
    console.log("Welcome to the JavaScript world!");
});

Memoization: Caching the results of function calls.

const memoizedAdd = (function() {
    const cache = {};
    return function(x, y) {
        const key = x + ',' + y;
        if (key in cache) {
            return cache[key];
        }
        const result = x + y;
        cache[key] = result;
        return result;
    };
})();

4. JavaScript Promises Cheat Sheet

Creating a Promise:

const promise = new Promise((resolve, reject) => {
    // Asynchronous operation
    if (success) {
        resolve("Success");
    } else {
        reject("Error");
    }
});

Using Promises:

promise.then(result => {
    console.log(result);
}).catch(error => {
    console.log(error);
});

Promise.all():

Resolves when all promises are fulfilled.

Promise.all([promise1, promise2]).then(results => {
    console.log(results);
});

Promise Chaining:

fetch("https://api.example.com/data")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));

Promise.race(): Resolves or rejects as soon as one of the promises in the array resolves or rejects.

const promise1 = new Promise((resolve) => setTimeout(resolve, 100, "one"));
const promise2 = new Promise((resolve) => setTimeout(resolve, 200, "two"));

Promise.race([promise1, promise2]).then(console.log); // "one"

5. JavaScript Asynchronous Functions Cheat Sheet

Async Function:

async function fetchData() {
    const response = await fetch("https://api.example.com/data");
    const data = await response.json();
    console.log(data);
}

Error Handling with 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.log(error);
    }
}

Using Async/Await with Fetch:

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("Fetch error: ", error);
    }
}

Parallel Execution with Promise.all():

async function fetchAll() {
    const [data1, data2] = await Promise.all([
        fetch("https://api.example.com/data1"),
        fetch("https://api.example.com/data2"),
    ]);
    console.log(data1, data2);
}

6. JavaScript Error Handling Cheat Sheet

Try/Catch:

try {
    // Code that may throw an error
} catch (error) {
    console.log("Error: ", error);
}

Throwing Errors:

function checkNumber(num) {
    if (num < 0) {
        throw new Error("Negative number not allowed");
    }
    return num;
}

Custom Error Classes:

class CustomError extends Error {
    constructor(message) {
        super(message);
        this.name = "CustomError";
    }
}

7. JavaScript JSON Cheat Sheet

Parsing JSON:

const jsonString = '{"name":"John", "age":30}';
const obj = JSON.parse(jsonString);

Stringifying JSON:

const obj = { name: "John", age: 30 };
const jsonString = JSON.stringify(obj);

Working with JSON:

const user = {
    name: "Alice",
    age: 30
};
const jsonString = JSON.stringify(user); // Convert to JSON
const parsedUser = JSON.parse(jsonString); // Convert back to object

8. JavaScript ES6 Features Cheat Sheet

Template Literals:

const name = "John";
const greeting = `Hello, ${name}!`;

Spread Operator:

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];

Rest Parameters:

function sum(...numbers) {
    return numbers.reduce((acc, num) => acc + num, 0);
}

Default Parameters:

function greet(name = "Guest") {
    console.log("Hello, " + name);
}

Modules:

// Exporting
export const pi = 3.14;

// Importing
import { pi } from './math.js';

Classes:

class Animal {
    constructor(name) {
        this.name = name;
    }
    speak() {
        console.log(this.name + " makes a noise.");
    }
}

class Dog extends Animal {
    speak() {
        console.log(this.name + " barks.");
    }
}

Promises and Async/Await:

const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("Success"), 2000);
});

myPromise.then(result => console.log(result));

9. JavaScript Regular Expressions Cheat Sheet

Creating a RegExp:

const regex = /[A-Z]/; // Matches any uppercase letter

Testing a String:

const str = "Hello";
console.log(regex.test(str)); // true

Matching:

const match = "Hello".match(/[A-Z]/); // ["H"]

Replacing:

const newStr = "Hello World".replace(/World/, "JavaScript"); // "Hello JavaScript"

Global and Case-Insensitive Flags:

const regexGlobal = /hello/gi; // g: global, i: case-insensitive

Basic Patterns:

Dot (.): Matches any single character except newline.

const regex = /a.b/; // Matches "acb", "axb", etc.

Caret (^): Matches the start of a string.

const regex = /^Hello/; // Matches "Hello" at the start of a string

Dollar Sign ($): Matches the end of a string.

const regex = /world$/; // Matches "world" at the end of a string

Character Classes:

Square Brackets ([]): Matches any one of the characters inside the brackets.

const regex = /[aeiou]/; // Matches any vowel

Negation ([^]): Matches any character not inside the brackets.

const regex = /[^aeiou]/; // Matches any consonant

Quantifiers:

Asterisk (*): Matches zero or more of the preceding element.

const regex = /ab*/; // Matches "a", "ab", "abb", etc.

Plus (+): Matches one or more of the preceding element.

const regex = /ab+/; // Matches "ab", "abb", but not "a"

Question Mark (?): Matches zero or one of the preceding element.

const regex = /ab?/; // Matches "a" or "ab"

Braces ({n}): Matches exactly n occurrences.

const regex = /a{2}/; // Matches "aa"

Braces with Range ({n,m}): Matches between n and m occurrences.

const regex = /a{1,3}/; // Matches "a", "aa", or "aaa"

Groups and Capturing:

Parentheses (()): Groups patterns and captures matched sub-expressions.

const regex = /(abc)+/; // Matches "abc", "abcabc", etc.

Non-Capturing Groups: Use (?:...) to group without capturing.

const regex = /(?:abc)+/; // Matches "abc", "abcabc", but doesn't capture the match

Lookaheads and Lookbehinds:

Negative Lookbehind ((?<!...)): Asserts that what precedes does not match the pattern.

const regex = /a(?!b)/; // Matches "a" only if not followed by "b"

Lookahead ((?=...)): Asserts that what follows matches the pattern.

const regex = /a(?=b)/; // Matches "a" only if followed by "b"

Negative Lookahead ((?!...)): Asserts that what follows does not match the pattern.

const regex = /(?<!b)a/; // Matches "a" only if not preceded by "b"

Lookbehind ((?<=...)): Asserts that what precedes matches the pattern.

const regex = /(?<=b)a/; // Matches "a" only if preceded by "b"

10. JavaScript Event Handling Cheat Sheet

Adding Event Listeners:

const button = document.querySelector('button');
button.addEventListener('click', function() {
    alert('Button clicked!');
});

Removing Event Listeners:

function handleClick() {
    alert('Button clicked!');
}

button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick);

Event Delegation:

document.getElementById('parent').addEventListener('click', function(event) {
    if (event.target.matches('button')) {
        alert('Button inside parent clicked!');
    }
});

Event Types:

Mouse Events:

  • click: Fired when the user clicks on an element.
  • dblclick: Fired when the user double-clicks on an element.
  • mouseover: Fired when the mouse pointer enters an element.
  • mouseout: Fired when the mouse pointer leaves an element.

Keyboard Events:

  • keydown: Fired when a key is pressed down.
  • keyup: Fired when a key is released.
  • keypress: Fired when a character key is pressed.

Form Events:

  • submit: Fired when a form is submitted.
  • change: Fired when an input element’s value changes.

Window Events:

  • load: Fired when the page is fully loaded.
  • resize: Fired when the window is resized.

Preventing Default Actions:

const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
    event.preventDefault(); // Prevents the form from submitting
    console.log('Form submitted!');
});
Event Bubbling and Capturing:
  • Bubbling: Events propagate from the target element up to the root.
  • Capturing: Events propagate from the root down to the target element.
document.getElementById('parent').addEventListener('click', function() {
    alert('Parent clicked!');
}, true); // Capturing phase

document.getElementById('child').addEventListener('click', function() {
    alert('Child clicked!');
}); // Bubbling phase

Event Delegation:

document.getElementById('parent').addEventListener('click', function(event) {
    if (event.target.matches('button')) {
        console.log('Button clicked: ' + event.target.textContent);
    }
});

Using this Keyword:

const button = document.querySelector('button');
button.addEventListener('click', function() {
    console.log(this.textContent); // Refers to the button that was clicked
});

11. JavaScript Date and Time Cheat Sheet

Creating a Date Object:

const date = new Date(); // Current date and time
const specificDate = new Date('2023-01-01'); // Specific date

Getting Date Components:

const year = date.getFullYear();
const month = date.getMonth(); // 0-11
const day = date.getDate();

Formatting Dates:

const formattedDate = date.toLocaleDateString(); // Format as locale date

Comparing Dates:

const date1 = new Date('2023-01-01');
const date2 = new Date('2023-02-01');
console.log(date1 < date2); // true

12. JavaScript Math Cheat Sheet

Math Constants:

  • Math.LOG10E: Base 10 logarithm of e.
  • Math.PI: The value of Ï€ (Pi).
  • Math.E: The value of e (Euler’s number).
  • Math.LN2: Natural logarithm of 2.
  • Math.LN10: Natural logarithm of 10.
  • Math.LOG2E: Base 2 logarithm of e.

Additional Math Methods:

Rounding:

Math.round(4.5); // 5
Math.floor(4.9); // 4
Math.ceil(4.1); // 5

Random Numbers:

Math.random(); // Random number between 0 and 1
Math.floor(Math.random() * 100); // Random number between 0 and 99

Power and Exponents:

Math.pow(2, 3); // 8 (2 raised to the power of 3)
Math.sqrt(16); // 4 (Square root of 16)

Trigonometric Functions:

Math.sin(0); // 0
Math.cos(Math.PI); // -1
Math.tan(Math.PI / 4); // 1

Converting Radians to Degrees:

function radiansToDegrees(radians) {
    return radians * (180 / Math.PI);
}

Clamping a Value:

function clamp(value, min, max) {
    return Math.min(Math.max(value, min), max);
}

Finding the Maximum and Minimum:

Math.max(1, 2, 3); // 3
Math.min(1, 2, 3); // 1

Miscellaneous Math Functions:

Math.hypot(...): Returns the square root of the sum of squares of its arguments.

Math.hypot(3, 4); // 5 (3-4-5 triangle)

Math.abs(x): Returns the absolute value of x.

Math.sign(x): Returns 1 for positive numbers, -1 for negative numbers, and 0 for zero.


Conclusion

This expanded cheat sheet provides a broader overview of JavaScript, covering fundamental concepts, advanced topics, and practical examples. Feel free to modify or extend it further based on specific needs or additional areas of focus!

Leave a Reply

Your email address will not be published. Required fields are marked *