### Install pnpm on Linux/macOS Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/src/pages/contributing.md Installs the pnpm package manager using curl. This is a prerequisite for running the project locally. It fetches and executes an installation script. ```shell curl -fsSL https://get.pnpm.io/install.sh | sh - ``` -------------------------------- ### Clone and Install Project Dependencies Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/src/pages/contributing.md Clones the project repository and installs all necessary dependencies using pnpm. This step is crucial for setting up the development environment. ```shell git clone https://github.com/wilfredinni/javascript-cheatsheet.git cd javascript-cheatsheet pnpm install ``` -------------------------------- ### Install pnpm on Windows (PowerShell) Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/src/pages/contributing.md Installs the pnpm package manager using PowerShell. This is a prerequisite for running the project locally. It fetches and executes an installation script. ```shell iwr https://get.pnpm.io/install.ps1 -useb | iex ``` -------------------------------- ### Start Anchor (^): JavaScript Regex Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/regular-expressions.md The start anchor (^) matches the beginning of the string. It's useful for ensuring a pattern appears at the very start of the text being tested. This example demonstrates its usage with the test() method. ```javascript let regex = /^abc/; let str = 'abcdef'; console.log(regex.test(str)); // true ``` -------------------------------- ### JavaScript Switch Statement Example Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/control-flow.md Illustrates the switch statement with a practical example using a string variable. It demonstrates how different cases are matched and executed, including the role of the 'break' keyword to prevent fall-through. ```javascript let fruit = 'apple'; switch (fruit) { case 'banana': console.log('I am a banana'); break; case 'apple': console.log('I am an apple'); break; default: console.log('I am not a banana or an apple'); } ``` -------------------------------- ### JavaScript Object Example Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/objects.md Demonstrates a basic JavaScript object with properties (maker, model, year) and a method (startEngine). ```javascript let car = { maker: "Toyota", model: "Camry", year: 2020, startEngine: function() { return "Engine started"; } }; ``` -------------------------------- ### JavaScript Ternary Operator Example Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/control-flow.md Provides a practical example of the ternary operator, assigning a string value to a variable based on a numerical comparison. This highlights its utility for short, conditional assignments. ```javascript let a = 10; let result = a > 5 ? 'a is greater than 5' : 'a is not greater than 5'; console.log(result); ``` -------------------------------- ### JavaScript Array flatMap with Strings Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md This example shows how flatMap() can be used to split strings into words and flatten the resulting arrays into a single new array. ```javascript let arr = ["it's Sunny in", "", "California"]; let newArr = arr.flatMap(x => x.split(' ')); // newArr is ["it's", "Sunny", "in", "", "California"] ``` -------------------------------- ### JavaScript: For Loop Syntax and Example Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/control-flow.md The 'for' loop is used for executing a block of code a specific number of times. It consists of initialization, a condition check, and a final expression executed after each iteration. ```javascript for (initialization; condition; finalExpression) { // code to be executed } // Example: for (let i = 0; i < 5; i++) { console.log(i); } // Output: 0, 1, 2, 3, 4 ``` -------------------------------- ### Clear JavaScript Set Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/sets.md Demonstrates how to remove all elements from a JavaScript Set using the `clear()` method. The example shows checking the Set's size before and after the operation. ```javascript let mySet = new Set([1, 2, 3, 4, 5]); console.log(mySet.size); // Outputs: 5 mySet.clear(); console.log(mySet.size); // Outputs: 0 ``` -------------------------------- ### JavaScript Array flatMap with Numbers Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. This example demonstrates mapping numbers to their doubles. ```javascript let arr = [1, 2, 3, 4]; let newArr = arr.flatMap(x => [x * 2]); // newArr is [2, 4, 6, 8] ``` -------------------------------- ### Array Length - Getting Length Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/arrays.md Demonstrates how to retrieve the number of elements in a JavaScript array using the `.length` property. ```javascript let fruits = ['apple', 'banana', 'cherry']; console.log(fruits.length); // logs 3 ``` -------------------------------- ### JavaScript: Do...While Loop Syntax and Example Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/control-flow.md The 'do...while' loop executes a block of code once, then repeatedly executes it as long as a specified condition remains true. It guarantees at least one execution of the loop body. ```javascript do { // code to be executed } while (condition); // Example: let i = 0; do { console.log(i); i++; } while (i < 5); // Output: 0, 1, 2, 3, 4 ``` -------------------------------- ### JavaScript: For Loop vs. Array Methods (Map Example) Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/control-flow.md Compares the use of a 'for' loop with array methods like 'map' for transforming array elements. 'For' loops offer more control and potential performance benefits, while array methods provide declarative readability and immutability. ```javascript // Using For Loop: let arrFor = [1, 2, 3, 4, 5]; for (let i = 0; i < arrFor.length; i++) { arrFor[i] = arrFor[i] * 2; } // arrFor is now [2, 4, 6, 8, 10] // Using Map Method: let arrMap = [1, 2, 3, 4, 5]; let doubled = arrMap.map(num => num * 2); // doubled is [2, 4, 6, 8, 10], arrMap remains unchanged ``` -------------------------------- ### JavaScript Array entries() Iterator Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md The entries() method returns a new Array Iterator object that contains the key/value pairs (index and element) for each index in the array. The example iterates through these entries. ```javascript let array = ['a', 'b', 'c']; let iterator = array.entries(); for (let [index, value] of iterator) { console.log(`index: ${index}, value: ${value}`); // logs 'index: 0, value: a', then 'index: 1, value: b', then 'index: 2, value: c' } ``` -------------------------------- ### JavaScript While Loop Example Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/control-flow.md Shows a practical implementation of a while loop that iterates and prints numbers from 0 to 4. It includes incrementing a counter variable to ensure the loop condition eventually becomes false, preventing an infinite loop. ```javascript let i = 0; while (i < 5) { console.log(i); i++; } ``` -------------------------------- ### JavaScript Array keys() Iterator Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md The keys() method returns a new Array Iterator object that contains the keys (indices) for each index in the array. The example iterates through these keys. ```javascript let array = ['a', 'b', 'c']; let iterator = array.keys(); for (let key of iterator) { console.log(key); // logs 0, then 1, then 2 } ``` -------------------------------- ### JavaScript Array.from String Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object. This example creates an array from a string. ```javascript let string = 'hello'; let array = Array.from(string); // array is ['h', 'e', 'l', 'l', 'o'] ``` -------------------------------- ### Grouping (()): JavaScript Regex Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/regular-expressions.md Parentheses () define a capturing group, allowing you to group parts of a regex or capture matched substrings. This example demonstrates basic grouping. The test() method checks if the grouped pattern exists. ```javascript let regex = /(abc)/; let str = 'abcdef'; console.log(regex.test(str)); // true ``` -------------------------------- ### JavaScript Array Join Method Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md The join() method concatenates all elements of an array into a string. Elements are separated by a specified separator; the default is a comma. Examples show default and custom separator usage. ```javascript let fruits = ['apple', 'banana', 'orange']; let fruitsString = fruits.join(); // fruitsString is 'apple,banana,orange' ``` ```javascript let fruits = ['apple', 'banana', 'orange']; let fruitsString = fruits.join(' - '); // fruitsString is 'apple - banana - orange' ``` -------------------------------- ### JavaScript Single-line Comments Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/basics.md Single-line comments in JavaScript start with two forward slashes (`//`). Everything following `//` on the same line is ignored by the JavaScript interpreter. They are used for brief explanations or to temporarily disable a line of code. ```javascript // This is a single-line comment ``` -------------------------------- ### JavaScript Array IndexOf Method Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md The indexOf() method searches an array for a specific element and returns its first index. If the element is not found, it returns -1. Examples show finding an element and handling cases where it's not present. ```javascript let fruits = ['apple', 'banana', 'orange']; let index = fruits.indexOf('banana'); // index is 1 ``` ```javascript let fruits = ['apple', 'banana', 'orange']; let index = fruits.indexOf('pineapple'); // index is -1 ``` -------------------------------- ### JavaScript console.time: Measuring Code Execution Time Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/debugging.md Measures the time taken by a block of code to execute when used in conjunction with console.timeEnd(). It requires a label string that must match between the start and end calls. This provides a simple way to benchmark code performance. ```javascript console.time('Array processing'); // Some array processing to measure let array = []; for(let i = 0; i < 1000000; i++) { array.push(i); } console.timeEnd('Array processing'); ``` -------------------------------- ### Get Map Value Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/map.md The `get(key)` method retrieves the value of the specified key. Returns `undefined` if the key does not exist. ```javascript map.get('age') map.get('none') ``` -------------------------------- ### Create Directory Async Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/directory-files.md Creates a directory at the specified path using `fs.mkdir`. The `recursive: true` option ensures that parent directories are created if they don't exist. The operation is asynchronous, returning a promise that resolves on success or rejects on error. ```javascript const fs = require('fs').promises; async function createDirectoryAsync(dirPath) { try { await fs.mkdir(dirPath, { recursive: true }); console.log('Directory created successfully'); } catch (err) { console.error('An error occurred:', err); } } createDirectoryAsync('exampleDir'); ``` -------------------------------- ### Create Map Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/map.md Creates an empty Map instance. ```javascript const map = new Map() ``` -------------------------------- ### Stage, Commit, and Push Changes Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/src/pages/contributing.md Stages all modified files, commits them with a descriptive message, and pushes the changes to the remote repository. This is the final step before creating a pull request. ```shell git add . git commit -m 'succinct explanation of what changed' git push origin fix_bug ``` -------------------------------- ### Get Map Size Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/map.md The `size` property returns the number of key-value pairs in a map. ```javascript map.size ``` -------------------------------- ### Declare and Initialize JavaScript Sets Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/sets.md Shows how to declare an empty Set using `new Set()` and how to initialize a Set with values from an iterable, such as an array. Sets automatically handle uniqueness. ```javascript // Declare an empty Set let set1 = new Set(); // Declare a Set with initial values let set2 = new Set([1, 2, 3, 4, 5]); console.log(set1); // Outputs: Set(0) {} console.log(set2); // Outputs: Set(5) { 1, 2, 3, 4, 5 } ``` -------------------------------- ### Create and Checkout a New Branch Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/src/pages/contributing.md Creates a new Git branch for making changes and switches to it. This is standard practice for isolating development work before submitting a pull request. ```shell git branch fix_bug git checkout fix_bug ``` -------------------------------- ### Initialize Map Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/map.md Initializes a Map with an array of key-value pairs. ```javascript const map = new Map([ ['id', 1], ['name', 'Alice'], ]) ``` -------------------------------- ### String Substitution with console.log Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/debugging.md Illustrates the use of string substitution specifiers (like %s for strings) within console.log() for formatted output, similar to printf in C. This allows for cleaner, more readable log messages. ```javascript let name = 'Alice'; console.log('Hello, %s', name); // Outputs: Hello, Alice ``` -------------------------------- ### OR (|): JavaScript Regex Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/regular-expressions.md The OR operator (|) acts as a logical OR, matching either the pattern before it or the pattern after it. It's used for alternatives. This example tests if a string matches 'abc' or 'def'. ```javascript let regex = /abc|def/; let str1 = 'abc'; let str2 = 'def'; console.log(regex.test(str1)); // true console.log(regex.test(str2)); // true ``` -------------------------------- ### Check File/Directory Existence (Node.js) Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/directory-files.md Shows how to check if a file or directory exists using Node.js's `fs.promises.access`. The `checkExists` function uses a try-catch block to handle the promise returned by `fs.access`, logging whether the path exists or not. ```javascript const fs = require('fs').promises; async function checkExists(path) { try { await fs.access(path); console.log('The file or directory exists.'); } catch { console.log('The file or directory does not exist.'); } } // Example usage: checkExists('example.txt'); ``` -------------------------------- ### Declare variable with let Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/basics.md Demonstrates declaring a variable using the `let` keyword in JavaScript. Variables declared with `let` are block-scoped and can be reassigned. ```javascript let age = 25; ``` -------------------------------- ### JavaScript Array values() Iterator Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md The values() method returns a new Array Iterator object that contains the values for each index in the array. The example iterates through these values. ```javascript let array = ['a', 'b', 'c']; let iterator = array.values(); for (let value of iterator) { console.log(value); // logs 'a', then 'b', then 'c' } ``` -------------------------------- ### JavaScript Function Parameters Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/functions.md Illustrates how to define parameters in a function signature and pass arguments when calling the function. Parameters act as placeholders for values received by the function. ```javascript function add(a, b) { return a + b; } let sum = add(1, 2); // 1 is the argument for 'a', and 2 is the argument for 'b' ``` -------------------------------- ### Write File Asynchronously with Node.js fs Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/directory-files.md Shows how to write data to a file asynchronously using `fs.promises.writeFile` in Node.js. This function overwrites the file if it exists or creates it if it doesn't. Error handling is included. ```javascript const fs = require('fs').promises; async function writeFileAsync(filePath, content) { try { await fs.writeFile(filePath, content); console.log('File written successfully'); } catch (err) { console.error('An error occurred:', err); } } writeFileAsync('example.txt', 'Hello, World!'); ``` -------------------------------- ### JavaScript Array Reverse Method Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md The reverse() method reverses the order of elements in an array in place, mutating the original array. The example demonstrates reversing an array of strings. ```javascript let fruits = ['apple', 'banana', 'orange']; fruits.reverse(); // fruits is now ['orange', 'banana', 'apple'] ``` -------------------------------- ### Get the Size of a JavaScript Set Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/sets.md Shows how to retrieve the number of elements currently stored in a JavaScript Set using the `size` property. This property provides the current count of unique values. ```javascript let mySet = new Set([1, 2, 3, 4, 5]); console.log(mySet.size); // Outputs: 5 ``` -------------------------------- ### One or More (+): JavaScript Regex Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/regular-expressions.md The plus (+) quantifier matches the preceding element one or more times. It requires at least one occurrence of the pattern. This example checks for strings containing one or more 'a' characters. ```javascript let regex = /a+/; let str = 'aaaabc'; console.log(regex.test(str)); // true ``` -------------------------------- ### Array Declaration - Constructor Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/arrays.md Shows how to declare an array using the `new Array()` constructor, which is less common and more verbose than the literal syntax. ```javascript let fruits = new Array('apple', 'banana', 'cherry'); ``` -------------------------------- ### Javascript String Slice Method Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/manipulating-strings.md The `slice` method extracts a section of a string and returns it as a new string, without modifying the original. It takes a start index (inclusive) and an end index (exclusive). ```javascript let str = "Hello, World!"; let slicedStr = str.slice(7, 12); console.log(slicedStr); // Outputs: "World" ``` -------------------------------- ### Logging Objects with console.log Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/debugging.md Explains how to log entire JavaScript objects using console.log(). The console typically formats objects for better readability, showing key-value pairs. ```javascript let obj = {a: 1, b: 2, c: 3}; console.log(obj); // Outputs: { a: 1, b: 2, c: 3 } ``` -------------------------------- ### Append to File Asynchronously with Node.js fs Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/directory-files.md Illustrates appending content to an existing file asynchronously using `fs.promises.appendFile` in Node.js. If the file does not exist, it is created. Error handling is provided. ```javascript const fs = require('fs').promises; async function appendToFileAsync(filePath, content) { try { await fs.appendFile(filePath, content); console.log('File updated successfully'); } catch (err) { console.error('An error occurred:', err); } } appendToFileAsync('example.txt', ' More content'); ``` -------------------------------- ### Zero or More (*): JavaScript Regex Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/regular-expressions.md The asterisk (*) quantifier matches the preceding element zero or more times. This is useful for optional characters or sequences that can repeat. The example tests a string against a pattern allowing zero or more 'a' characters. ```javascript let regex = /a*/; let str = 'aaaabc'; console.log(regex.test(str)); // true ``` -------------------------------- ### Simple Unit Test with Jest Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/debugging.md Demonstrates a basic unit test using the Jest framework. It verifies that a `sum` function correctly adds two numbers. The `test` function defines the test case, while `expect` and `toBe` assert the expected outcome. This snippet assumes a `./sum` module is available. ```javascript const sum = require('./sum'); test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); }); ``` -------------------------------- ### Negative Lookahead ((?!)): JavaScript Regex Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/regular-expressions.md Negative lookahead (?! ) asserts that the pattern inside the lookahead must NOT match immediately after the current position, without consuming characters. This example checks if 'abc' is NOT followed by 'def'. ```javascript let regex = /abc(?!def)/; let str = 'abcghi'; console.log(regex.test(str)); // true ``` -------------------------------- ### Positive Lookahead ((?=)): JavaScript Regex Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/regular-expressions.md Positive lookahead (?=) asserts that the pattern inside the lookahead must match immediately after the current position, but it doesn't consume characters. This example checks if 'abc' is followed by 'def'. ```javascript let regex = /abc(?=def)/; let str = 'abcdef'; console.log(regex.test(str)); // true ``` -------------------------------- ### Watch File for Changes (Node.js) Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/directory-files.md Demonstrates how to use Node.js's `fs.watch` to monitor a file for changes. The callback function receives the event type ('rename' or 'change') and the filename. Note that `fs.watch` behavior can vary across platforms and is not always reliable; consider libraries like `chokidar` for more robust solutions. ```javascript const fs = require('fs'); fs.watch('example.txt', (eventType, filename) => { console.log(`Event type is: ${eventType}`); if (filename) { console.log(`Filename provided: ${filename}`); } else { console.log('Filename not provided'); } }); ``` -------------------------------- ### Read File Asynchronously with Node.js fs Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/directory-files.md Demonstrates reading a file's content asynchronously using the `fs.promises.readFile` method in Node.js. It handles potential errors during the file read operation. ```javascript const fs = require('fs').promises; async function readFileAsync(filePath) { try { const data = await fs.readFile(filePath, 'utf8'); console.log('File content:', data); } catch (err) { console.error('An error occurred:', err); } } readFileAsync('example.txt'); ``` -------------------------------- ### Array Fill Method Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md The `fill()` method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It modifies the array in place and returns the modified array. ```javascript let numbers = [1, 2, 3, 4, 5]; numbers.fill(0); // numbers is now [0, 0, 0, 0, 0] console.log(numbers); ``` ```javascript let numbers = [1, 2, 3, 4, 5]; numbers.fill(0, 1, 3); // numbers is now [1, 0, 0, 4, 5] console.log(numbers); ``` -------------------------------- ### Array Declaration - Array.of() Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/arrays.md Illustrates creating a new Array instance from a variable number of arguments using the `Array.of()` static method. ```javascript let fruits = Array.of('apple', 'banana', 'cherry'); ``` -------------------------------- ### Non-Capturing Group ((?:)): JavaScript Regex Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/regular-expressions.md A non-capturing group (?:) groups parts of a regex without capturing the matched substring. This is useful for applying quantifiers to a sequence without storing the result. The example tests a non-capturing group. ```javascript let regex = /(?:abc)/; let str = 'abcdef'; console.log(regex.test(str)); // true ``` -------------------------------- ### Object Declaration: Constructor Syntax Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/objects.md Declares an object using the `new Object()` constructor and assigning properties individually. ```javascript let obj = new Object(); obj.key1 = 'value1'; obj.key2 = 'value2'; obj.key3 = 'value3'; ``` -------------------------------- ### Iterate Map using entries() Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/map.md Iterates over the map's key-value pairs in insertion order using the `entries()` method. ```javascript const map = new Map() map.set('name', 'Bob').set('age', 20) for (let [key, value] of map.entries()) { console.log(`${key}: ${value}`) } ``` -------------------------------- ### Between N and M ({nm}): JavaScript Regex Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/regular-expressions.md The curly braces {n,m} quantifier matches the preceding element at least n times and at most m times. It defines a specific range for repetition. This example checks for two or three 'a' characters. ```javascript let regex = /a{2,3}/; let str = 'aaaabc'; console.log(regex.test(str)); // true ``` -------------------------------- ### Exactly N ({n}): JavaScript Regex Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/regular-expressions.md The curly braces {n} quantifier matches the preceding element exactly n times. This is used for precise repetition counts. The example looks for exactly two 'a' characters. ```javascript let regex = /a{2}/; let str = 'aaaabc'; console.log(regex.test(str)); // true ``` -------------------------------- ### Logging Multiple Values with console.log Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/debugging.md Shows how to pass multiple arguments to console.log() to display several values simultaneously. This is useful for correlating different variables in a single log statement. ```javascript let x = 10; let y = 20; console.log(x, y); // Outputs: 10 20 ``` -------------------------------- ### Iterate Over a JavaScript Set Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/sets.md Presents multiple ways to iterate through the elements of a JavaScript Set, including using a `for...of` loop, the `forEach()` method, and converting the Set to an array using the spread operator. ```javascript let mySet = new Set([1, 2, 3, 4, 5]); // Using for...of loop console.log('Using for...of:'); for (let value of mySet) { console.log(value); } // Using forEach method console.log('Using forEach:'); mySet.forEach(function(value) { console.log(value); }); // Using spread operator to convert to array console.log('Using spread operator:'); let array = [...mySet]; array.forEach(function(value) { console.log(value); }); ``` -------------------------------- ### Handle Async Errors with Async/Await in JavaScript Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/error-handling.md Illustrates error handling in asynchronous JavaScript using the async/await syntax. This method allows the use of standard try/catch blocks, making asynchronous error management resemble synchronous code structure for improved readability and maintainability. ```javascript async function performAsyncOperations() { try { const result = await doSomething(); const newResult = await doSomethingElse(result); await doAnotherThing(newResult); console.log('Operations completed successfully.'); } catch (error) { console.error('An error occurred during async operations:', error); } } performAsyncOperations(); ``` -------------------------------- ### JavaScript Array Splice Method Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md The splice() method modifies an array by removing, replacing, or adding elements. It mutates the original array and returns an array of deleted elements. Examples cover removing, adding, and replacing elements. ```javascript let fruits = ['apple', 'banana', 'orange', 'pineapple', 'mango']; let removedFruits = fruits.splice(2, 2); // removedFruits is ['orange', 'pineapple'], fruits is ['apple', 'banana', 'mango'] ``` ```javascript let fruits = ['apple', 'banana', 'mango']; fruits.splice(2, 0, 'orange', 'pineapple'); // fruits is ['apple', 'banana', 'orange', 'pineapple', 'mango'] ``` ```javascript let fruits = ['apple', 'banana', 'mango']; fruits.splice(1, 1, 'orange'); // fruits is ['apple', 'orange', 'mango'] ``` -------------------------------- ### JavaScript if-else Statement Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/control-flow.md Demonstrates the use of if, else if, and else statements to execute different blocks of code based on specified conditions. This structure allows for sequential evaluation of conditions, executing the first true block encountered. ```javascript let a = 4; if (a > 5) { console.log('a is greater than 5'); } else if (a == 5) { console.log('a is equal to 5'); } else { console.log('a is less than 5'); } ``` -------------------------------- ### JavaScript console.group: Grouping Log Messages Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/debugging.md Groups related log messages in the console, allowing for hierarchical organization. Use console.group() to start a new group and console.groupEnd() to close the most recent group. Nested groups are supported for complex logging structures. ```javascript console.group('Processing array'); console.log('Array has', array.length, 'elements'); console.log('First element:', array[0]); console.groupEnd(); ``` -------------------------------- ### Overwrite File Async Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/directory-files.md Overwrites a file at the specified path with new content using `fs.writeFile`. This asynchronous operation returns a promise that resolves upon successful update or rejects if an error occurs, which is then logged to the console. ```javascript const fs = require('fs').promises; async function overwriteFileAsync(filePath, content) { try { await fs.writeFile(filePath, content); console.log('File updated successfully'); } catch (err) { console.error('An error occurred:', err); } } overwriteFileAsync('example.txt', 'New content'); ``` -------------------------------- ### JavaScript: Compare Arrow vs Regular Function Syntax Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/functions.md Highlights the syntactic differences between a regular function expression and an equivalent arrow function. Arrow functions offer a shorter, more readable syntax for many cases. ```javascript // Regular function let addRegular = function(a, b) { return a + b; } // Arrow function let addArrow = (a, b) => a + b; ``` -------------------------------- ### JavaScript Array FindIndex Method Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md The findIndex() method returns the index of the first element in an array that satisfies a provided testing function. It returns -1 if no element satisfies the condition. Examples demonstrate finding an element and handling cases where no element matches. ```javascript let numbers = [5, 12, 8, 130, 44]; let isLargeNumber = (element) => element > 13; let index = numbers.findIndex(isLargeNumber); // index is 3 ``` ```javascript let numbers = [5, 12, 8, 10, 4]; let isLargeNumber = (element) => element > 13; let index = numbers.findIndex(isLargeNumber); // index is -1 ``` -------------------------------- ### Extract portion of array with slice() - JavaScript Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/array-methods.md The slice() method returns a shallow copy of a portion of an array into a new array object, selected from a start index up to (but not including) an end index. The original array is not modified. If the end index is omitted, it slices to the end of the array. ```javascript let fruits = ['apple', 'banana', 'orange', 'pineapple', 'mango']; let citrusFruits = fruits.slice(2, 4); // citrusFruits is ['orange', 'pineapple'] ``` ```javascript let fruits = ['apple', 'banana', 'orange', 'pineapple', 'mango']; let someFruits = fruits.slice(2); // someFruits is ['orange', 'pineapple', 'mango'] ``` -------------------------------- ### Declare variable with var Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/basics.md Demonstrates declaring a variable using the `var` keyword in JavaScript. Variables declared with `var` are function-scoped and can be reassigned. ```javascript var name = "John" ``` -------------------------------- ### Logging Arrays with console.log Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/debugging.md Demonstrates logging JavaScript arrays with console.log(). The console usually displays arrays in a readable format, showing their elements. ```javascript let arr = [1, 2, 3, 4, 5]; console.log(arr); // Outputs: [ 1, 2, 3, 4, 5 ] ``` -------------------------------- ### Read Directory Async Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/directory-files.md Reads the contents of a directory at the given path using `fs.readdir`. This asynchronous function returns a promise that resolves with an array of filenames within the directory. Errors are caught and logged. ```javascript const fs = require('fs').promises; async function readDirectoryAsync(dirPath) { try { const files = await fs.readdir(dirPath); console.log('Directory content:', files); } catch (err) { console.error('An error occurred:', err); } } readDirectoryAsync('exampleDir'); ``` -------------------------------- ### Using console.info for Informational Messages Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/debugging.md Introduces console.info() for logging informational messages. In many environments, it functions identically to console.log(), but may be styled differently to denote information. ```javascript console.info('This is an informational message'); ``` -------------------------------- ### Iterate Map using keys() Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/map.md Iterates over the map's keys in insertion order using the `keys()` method. ```javascript const map = new Map() map.set('name', 'Bob').set('age', 20) for (const key of map.keys()) { console.log(`${key}`) } ``` -------------------------------- ### Logging Variable Values with console.log Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/debugging.md Demonstrates the basic usage of console.log() to print the value of a single variable to the console. This is a fundamental debugging technique for inspecting variable states. ```javascript let x = 10; console.log(x); // Outputs: 10 ``` -------------------------------- ### JavaScript console.trace: Outputting Stack Traces Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/debugging.md Outputs a stack trace to the console, showing the execution path that led to the call. This is invaluable for debugging, as it clearly illustrates the sequence of function calls. ```javascript function firstFunction() { secondFunction(); } function secondFunction() { thirdFunction(); } function thirdFunction() { console.trace(); } firstFunction(); ``` -------------------------------- ### JavaScript Exponentiation Operator (**) Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/basics.md Raises the first number to the power of the second number. It calculates base to the exponent power. This operator is a modern addition to JavaScript. ```javascript let result = 5 ** 2; // result is 25 ``` -------------------------------- ### Call a JavaScript Function Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/functions.md Executes a defined function by using its name followed by parentheses. Arguments can be passed within the parentheses to provide values for the function's parameters. ```javascript greet(); // Calls the function and prints "Hello, world!" to the console ``` -------------------------------- ### Basic Try-Catch for Error Handling in JavaScript Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/error-handling.md Demonstrates the fundamental try...catch block structure for executing code that might fail and handling potential errors. The try block contains the risky code, and the catch block processes any errors thrown. ```javascript try { // Code that may throw an error } catch (error) { // Code to handle the error } ``` -------------------------------- ### JavaScript Spread Operator: Array Expansion and Combination Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/arrays.md Demonstrates the use of the JavaScript spread operator (...) to create new arrays by expanding existing iterables. It shows how to add elements to an array and combine multiple arrays into a single new array. ```javascript let fruits = ['apple', 'banana', 'cherry']; let moreFruits = [...fruits, 'date', 'elderberry']; console.log(moreFruits); // logs ['apple', 'banana', 'cherry', 'date', 'elderberry'] ``` ```javascript let fruits1 = ['apple', 'banana']; let fruits2 = ['cherry', 'date']; let allFruits = [...fruits1, ...fruits2]; console.log(allFruits); // logs ['apple', 'banana', 'cherry', 'date'] ``` -------------------------------- ### Add Values to a JavaScript Set Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/sets.md Demonstrates the use of the `add()` method to insert new values into a JavaScript Set. Each value added is unique; duplicates are ignored. ```javascript let mySet = new Set(); mySet.add(1); mySet.add(2); mySet.add(3); console.log(mySet); // Outputs: Set(3) { 1, 2, 3 } ``` -------------------------------- ### Rename File Async Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/directory-files.md Renames a file from an old path to a new path using `fs.rename`. This asynchronous function returns a promise, and any errors during the renaming process are caught and reported. ```javascript const fs = require('fs').promises; async function renameFileAsync(oldPath, newPath) { try { await fs.rename(oldPath, newPath); console.log('File renamed successfully'); } catch (err) { console.error('An error occurred:', err); } } renameFileAsync('oldName.txt', 'newName.txt'); ``` -------------------------------- ### Delete Directory Async Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/directory-files.md Deletes a directory at the specified path using `fs.rmdir`. This function only works on empty directories; attempting to delete a non-empty directory will result in an error. The operation is asynchronous and logs any errors encountered. ```javascript const fs = require('fs').promises; async function deleteDirectoryAsync(dirPath) { try { await fs.rmdir(dirPath); console.log('Directory deleted successfully'); } catch (err) { console.error('An error occurred:', err); } } deleteDirectoryAsync('exampleDir'); ``` -------------------------------- ### JavaScript Division Operator (/) Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/basics.md Performs division between two numbers. It divides the first operand by the second. Division by zero results in Infinity. ```javascript let result = 10 / 5; // result is 2 ``` -------------------------------- ### JavaScript: Define Arrow Function with Parameters Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/functions.md Demonstrates an arrow function that accepts multiple parameters and implicitly returns the result of an expression. This provides a very compact way to write simple functions. ```javascript let add = (a, b) => a + b; let sum = add(1, 2); // sum is now 3 ``` -------------------------------- ### JavaScript: Define and Use Anonymous Function Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/functions.md Demonstrates defining an anonymous function and assigning it to a variable for later execution. This is a common pattern for function expressions. ```javascript let greet = function() { console.log("Hello, world!"); } greet(); // Calls the function and prints "Hello, world!" to the console ``` -------------------------------- ### Array Declaration - Array.from() Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/arrays.md Demonstrates creating a new Array instance from an array-like or iterable object using the `Array.from()` static method. ```javascript let fruits = Array.from(['apple', 'banana', 'cherry']); ``` -------------------------------- ### Iterate Map using for...of Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/map.md Iterates over each key-value pair in the map using a `for...of` loop with destructuring. ```javascript const map = new Map() map.set('name', 'Bob').set('age', 20) for (const [key, value] of map) { console.log(`${key}: ${value}`) } ``` -------------------------------- ### JavaScript: Compare Arrow vs Regular Function `this` Binding Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/functions.md Explains the critical difference in how `this` is bound. Regular functions have dynamic `this` binding, while arrow functions inherit `this` from their surrounding lexical scope, preventing common `this` issues. ```javascript // Regular function with dynamic 'this' let obj1 = { value: 'a', createAnonFunction: function() { return function() { console.log(this.value); }; } }; obj1.createAnonFunction()(); // undefined (this refers to global object or undefined in strict mode) // Arrow function with lexical 'this' let obj2 = { value: 'a', createArrowFunction: function() { return () => { console.log(this.value); }; } }; obj2.createArrowFunction()(); // 'a' (this is lexically bound from createArrowFunction) ``` -------------------------------- ### Object Declaration: Constructor Function Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/objects.md Defines a constructor function to create multiple objects with a consistent structure, initializing properties via arguments. ```javascript function MyObject(key1, key2, key3) { this.key1 = key1; this.key2 = key2; this.key3 = key3; } let obj = new MyObject('value1', 'value2', 'value3'); ``` -------------------------------- ### Using console.warn for Warning Messages Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/debugging.md Explains the use of console.warn() to log warning messages. This method is typically styled distinctively (e.g., yellow icon/text) to highlight potential issues that are not critical errors. ```javascript console.warn('This is a warning message'); ``` -------------------------------- ### JavaScript Function Return Value Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/functions.md Shows how the 'return' statement is used to end function execution and specify a value to be sent back to the caller. If no 'return' statement is present, the function implicitly returns 'undefined'. ```javascript function add(a, b) { return a + b; } let sum = add(1, 2); // sum is now 3 ``` -------------------------------- ### Array Indexes - Accessing Elements Source: https://github.com/wilfredinni/javascript-cheatsheet/blob/master/docs/cheatsheet/arrays.md Shows how to access individual elements within a JavaScript array using their zero-based numeric index. ```javascript let fruits = ['apple', 'banana', 'cherry']; console.log(fruits[0]); // logs 'apple' console.log(fruits[1]); // logs 'banana' console.log(fruits[2]); // logs 'cherry' ```