JS - Other

Include jQuery in the JavaScript Console

var jq = document.createElement('script');
jq.src = "https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);

// ... give time for script to load, then type (or see below for non wait option)
jQuery.noConflict();

IndexedDB API

IndexedDB is a low-level, asynchronous, NoSQL database in the browser for storing large amounts of structured data. It allows you to persistently store and query key-value pairs, objects, or files.


Features

  • Stores structured data, including objects and blobs.
  • Works asynchronously for non-blocking operations.
  • Supports transactions for data consistency.


Example: Basic CRUD Operations

// Open the database
let request = indexedDB.open("MyDatabase", 1);

request.onupgradeneeded = function (event) {
  let db = event.target.result;

  // Create an object store
  if (!db.objectStoreNames.contains("users")) {
    db.createObjectStore("users", { keyPath: "id" });
  }
};

request.onsuccess = function (event) {
  let db = event.target.result;

  // Add data
  let transaction = db.transaction("users", "readwrite");
  let store = transaction.objectStore("users");
  store.add({ id: 1, name: "Alice", age: 25 });

  // Read data
  let getRequest = store.get(1);
  getRequest.onsuccess = function () {
    console.log(getRequest.result); // { id: 1, name: "Alice", age: 25 }
  };

  // Update data
  store.put({ id: 1, name: "Alice Updated", age: 26 });

  // Delete data
  store.delete(1);
};

Intersection Observer API

The Intersection Observer API allows you to detect when an element enters or leaves the viewport. This is exceptionally useful for implementing infinite scroll.

<style>
 #load-more-trigger {
    height: 1px;
    width: 100%;
 }
</style>

<div id="content-container">
    <!-- Existing content items here -->
</div>
<div id="load-more-trigger"></div>


$(document).ready(function() {
    let loading = false; // Prevents multiple requests at once
    let observerOptions = {
        root: null, // Use the viewport as the root
        rootMargin: '0px', // No margin around the root
        threshold: 0.1 // Trigger when 10% of the target is visible
    };


    let observer = new IntersectionObserver(function(entries, observer) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting && !loading) {
                loading = true;
                loadMoreContent(); // Load more content when the trigger is in view
            }
        });
    }, observerOptions);


    // Start observing the trigger element
    observer.observe(document.querySelector('#load-more-trigger'));


    function loadMoreContent() {
        // Simulate an AJAX request to load more content
        $.ajax({
            url: 'path/to/your/api', // Replace with your content API or server endpoint
            method: 'GET',
            success: function(data) {
                // Append new content to the container
                $('#content-container').append(data);


                // Reset the loading flag
                loading = false;
            },
            error: function() {
                console.log('Error loading more content');
                loading = false;
            }
        });
    }
});


JavaScript Array Destructuring

const simpleArr = ['find', 'the', 'bug', 'pls']

const doubleArr = [
    ['find', 'the', 'bug', 'pls'],
    ['we', 'solved', 'it', '🔥']
]


Simple Array Destructuring.

const [firstValue, secondValue] = simpleArr
console.log(firstValue) // find
console.log(secondValue) // the


Jump values & assign new value.

const [, , thirdValue = 'nope'] = simpleArr
console.log(thirdValue) //bug


Example with new value:

const simpleArr = ['find', 'the', undefined, 'pls']
const [, , newValue = 'nope'] = simpleArr
console.log(newValue) // nope


Get Nested arrays from a double array.

const [firstArray, secondArray] = doubleArr
console.log(firstArray) // [ 'find', 'the', 'bug', 'pls' ]
console.log(secondArray) // [ 'we', 'solved', 'it', '🔥' ]


Get values from nested arrays.

const [[, , third], [, second]] = doubleArr
console.log(third) // bug
console.log(second) // solved

JavaScript Object Destructuring

const developer = {
  username: 'NotAbug',
  email: 'notabug@pls.com',
  networks: {
    instagram: {
      username: '@notABug-ig',
      link: 'https://instagram.com/notabug'
    },
    twitter: {
      username: '@notABug-tw',
      link: 'https://twitter.com/notabug'
    },
    youtube: {}
  }
}


Simple object destructuring.

const { username } = developer
console.log(username) // NotAbug


Nested destructuring and rename.

const { 
  networks: {
    instagram: { username: instagramUsername },
    twitter: { username: twitterUsername },
    youtube: { username: youtubeUsername = null }
  }
} = developer
console.log(instagramUsername) // @notABug-ig
console.log(twitterUsername) // @notABug-tw
console.log(youtubeUsername) // null


Destructuring and rest operator.

const { networks: { instagram, ...restNetworks } } = developer

const newInstagram = {
    username: '@definitelyNotABug',
    link: instagram.link
}

developer.networks = {
    ...restNetworks,
    instagram: newInstagram
}
console.log(developer.networks.instagram.username) // @definitelyNotABug

JavaScript Use Strict

"use strict"; Defines that JavaScript code should be executed in "strict mode".


The "use strict" Directive


The "use strict" directive was new in ECMAScript version 5.


It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.


The purpose of "use strict" is to indicate that the code should be executed in "strict mode".


With strict mode, you can not, for example, use undeclared variables.

Joining Arrays

arrays = [...array1, ...array2, ...array3]

Joining Objects

objects = [...object1, ...object2, ...object3]

JQuery UI - Uncaught TypeError: Cannot read property 'value' of undefined

Current Code :

// Announce the value in the liveRegion
label = ui.item.attr("aria-label") || item.value;
if (label && $.trim(label).length) {
  this.liveRegion.children().hide();
  $("<div>").text(label).appendTo(this.liveRegion);
}


Updated Code :  

// Announce the value in the liveRegion
if(typeof item !== "undefined") {
  label = ui.item.attr("aria-label") || item.value;
  if (label && $.trim(label).length) {
    this.liveRegion.children().hide();
    $("<div>").text(label).appendTo(this.liveRegion);
  }
}

JS Debugging

  1. console.assert() - Writes a message to the console, but only if an expression evaluates to false.
  2. console.clear() - Clears the console.
  3. console.count() - Write to the console the number of times that particular console.count() is called.
  4. console.dir() - Recognizes the object as an object and prints it's properties in the form of a clean expandable list.
  5. console.error() - Outputs an error message to the console.
  6. console.group() / groupEnd() - It's possible to group messages to avoid spam and mess in the console.
  7. console.info() - Writes a message to the console.
  8. console.log() - Writes (logs) a message to the console.
  9. console.table() - Print a visually nice table representation of an object.
  10. console.time() - Starts a timer (can track how long an operation takes).
  11. console.timeEnd() - Stops a timer that was previously started by console.time().
  12. console.warn() - Outputs a warning message to the console.


CSS styling the console

Use %c before a string. Example :

console.log('%cString','CSS')

Local and Session Storage APIs

These are simple, synchronous key-value storage mechanisms for storing small amounts of data in the browser.


Local Storage

  • Data persists until explicitly cleared.
  • ~5-10MB (varies per browser).
  • Across browser sessions.
// Set data
localStorage.setItem("username", "John");

// Get data
console.log(localStorage.getItem("username")); // Output: John

// Remove data
localStorage.removeItem("username");

// Clear all data
localStorage.clear();


Session Storage

  • Data lasts only for the session.
  • Same as Local Storage.
  • Only within the current session/tab.
// Set data
sessionStorage.setItem("sessionID", "12345");

// Get data
console.log(sessionStorage.getItem("sessionID")); // Output: 12345

// Remove data
sessionStorage.removeItem("sessionID");

// Clear all session data
sessionStorage.clear();