BaseCodeByte
Util

JS Utilities Lessons

The essential JS toolkit: jQuery, Lodash, Axios, Moment.js, Day.js, UUID and more.

Course outline

Tracks and lessons

Track 01beginner

jQuery

The library that tamed cross-browser JavaScript. jQuery is still the most deployed JS library.

01jQuery Introduction & SelectorsjQuery Overview jQuery by John Resig (2006) made JavaScript accessible by simplifying DOM manipulation, event handling, and AJAX. <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> // or: npm install jquerybeginner

jQuery Overview jQuery by John Resig (2006) made JavaScript accessible by simplifying DOM manipulation, event handling, and AJAX. <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> // or: npm install jquery

Example
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
// or: npm install jquery
Quiz

What does $(document).ready() ensure?

Which jQuery selector finds elements with a specific ID?

jQuery's strength is:

02DOM Manipulation & EventsjQuery DOM & Events // Text $('#p1').text(); // get $('#p1').text('New text'); // set // HTML $('#div1').html(); // get inner HTML $('#div1').html('&lt;b&gt;Bold&lt;/b&gt;'); // set inner HTML // Values (inputs) $('#input1').val(); // get $('#input1'beginner

jQuery DOM & Events // Text $('#p1').text(); // get $('#p1').text('New text'); // set // HTML $('#div1').html(); // get inner HTML $('#div1').html('&lt;b&gt;Bold&lt;/b&gt;'); // set inner HTML // Values (inputs) $('#input1').val(); // get $('#input1'

Example
// Text
$('#p1').text();               // get
$('#p1').text('New text');     // set

// HTML
$('#div1').html();             // get inner HTML
$('#div1').html('<b>Bold</b>');  // set inner HTML

// Values (inputs)
$('#input1').val();            // get
$('#input1').val('new value'); // set

// Attributes
$('img').attr('src');          // get
$('img').attr('src', 'new.jpg'); // set
$('a').removeAttr('href');

// CSS
$('#box').css('color');        // get
$('#box').css('color', 'red'); // set
Quiz

$("li").eq(2) returns:

Delegated events in jQuery (parent.on("click","li",fn)) are useful for:

$(this) inside a jQuery event handler refers to:

03AJAX & UtilitiesjQuery AJAX $.ajax({ url: '/api/users', method: 'GET', dataType: 'json', headers: { Authorization: 'Bearer token' }, success: (data) => console.log(data), error: (xhr, status, err) => console.error(err), complete: () => console.log('Done') });intermediate

jQuery AJAX $.ajax({ url: '/api/users', method: 'GET', dataType: 'json', headers: { Authorization: 'Bearer token' }, success: (data) => console.log(data), error: (xhr, status, err) => console.error(err), complete: () => console.log('Done') });

Example
$.ajax({
  url: '/api/users',
  method: 'GET',
  dataType: 'json',
  headers: { Authorization: 'Bearer token' },
  success: (data) => console.log(data),
  error: (xhr, status, err) => console.error(err),
  complete: () => console.log('Done')
});
Quiz

Which jQuery method gets JSON data from a URL in one line?

$.grep() is similar to native JS:

$.extend({}, a, b) does what?

Track 02beginner

Lodash / Underscore.js

A modern JavaScript utility library delivering modularity, performance, and extras. Lodash provides 200+ functions.

01Lodash IntroductionLodash Lodash (and its predecessor Underscore.js) provides utility functions for common programming tasks. While modern JS covers. npm install lodash import _ from 'lodash'; // or individual functions: import { cloneDeep, debounce } from 'lodash';beginner

Lodash Lodash (and its predecessor Underscore.js) provides utility functions for common programming tasks. While modern JS covers. npm install lodash import _ from 'lodash'; // or individual functions: import { cloneDeep, debounce } from 'lodash';

Example
npm install lodash
import _ from 'lodash';
// or individual functions:
import { cloneDeep, debounce } from 'lodash';
Quiz

What does _.get(obj, "a.b.c", "default") do if a.b.c is undefined?

_.cloneDeep is better than JSON.parse(JSON.stringify()) because:

_.debounce(fn, 300) means:

02Array & Collection MethodsLodash Arrays & Collections // Chunk: split array into groups of size n _.chunk([1,2,3,4,5], 2); // [[1,2],[3,4],[5]] // Flatten _.flatten([[1,[2]],[3]]); // [1,[2],3] _.flattenDeep([[1,[2,[3]]]]);// [1,2,3] // Unique _.uniq([1,2,2,3,3]); // [1,2,3] beginner

Lodash Arrays & Collections // Chunk: split array into groups of size n _.chunk([1,2,3,4,5], 2); // [[1,2],[3,4],[5]] // Flatten _.flatten([[1,[2]],[3]]); // [1,[2],3] _.flattenDeep([[1,[2,[3]]]]);// [1,2,3] // Unique _.uniq([1,2,2,3,3]); // [1,2,3]

Example
// Chunk: split array into groups of size n
_.chunk([1,2,3,4,5], 2);  // [[1,2],[3,4],[5]]

// Flatten
_.flatten([[1,[2]],[3]]);    // [1,[2],3]
_.flattenDeep([[1,[2,[3]]]]);// [1,2,3]

// Unique
_.uniq([1,2,2,3,3]);         // [1,2,3]
_.uniqBy(users, 'email');    // unique by email

// Difference, Intersection, Union
_.difference([1,2,3], [2]);  // [1,3]
_.intersection([1,2,3],[2,3]);// [2,3]
_.union([1,2], [2,3]);        // [1,2,3]

// Zip
_.zip(['a','b'],['x','y']);   // [['a','x'],['b','y']]

// Range
_.range(0, 10, 2);           // [0,2,4,6,8]

// Sample
_.sample([1,2,3,4]);         // random element
_.sampleSize([1,2,3,4], 2);  // 2 random elements
_.shuffle([1,2,3,4,5]);
Quiz

_.chunk([1,2,3,4,5], 2) returns:

_.groupBy(users, "dept") returns:

_.uniqBy(arr, "email") removes:

03Object & Function UtilitiesLodash Objects & Functions _.pick(user, ['name','email']); // only those keys _.omit(user, ['password','ssn']); // exclude those keys _.merge({ a:1, b:{x:1} }, { b:{y:2}, c:3 }); // { a:1, b:{x:1,y:2}, c:3 } (deep merge) _.defaults({ a:1 }, { a:99, bintermediate

Lodash Objects & Functions _.pick(user, ['name','email']); // only those keys _.omit(user, ['password','ssn']); // exclude those keys _.merge({ a:1, b:{x:1} }, { b:{y:2}, c:3 }); // { a:1, b:{x:1,y:2}, c:3 } (deep merge) _.defaults({ a:1 }, { a:99, b

Example
_.pick(user, ['name','email']);  // only those keys
_.omit(user, ['password','ssn']); // exclude those keys

_.merge({ a:1, b:{x:1} }, { b:{y:2}, c:3 });
// { a:1, b:{x:1,y:2}, c:3 }  (deep merge)

_.defaults({ a:1 }, { a:99, b:2 });
// { a:1, b:2 }  (existing values not overwritten)

_.mapValues({ a:1, b:2, c:3 }, v => v * 2);
// { a:2, b:4, c:6 }

_.invert({ a:'1', b:'2' });   // { '1':'a', '2':'b' }
_.isEmpty({});                 // true
_.isEqual({a:1}, {a:1});      // true (deep equal)
Quiz

_.pick(obj, ["a","b"]) returns:

_.once(fn) ensures the function:

What does _.memoize do?

Track 03beginner

Modernizr

Modernizr detects HTML5 and CSS3 features in the browser so you can write conditional.

01Feature Detection with ModernizrModernizr — Feature Detection Modernizr tests for browser feature support so you can use the best API available or fall. &lt;!-- Build a custom bundle at modernizr.com --&gt; &lt;script src="modernizr-custom.js"&gt;&lt;/script&gt; &lt;!-- Modernizr abeginner

Modernizr — Feature Detection Modernizr tests for browser feature support so you can use the best API available or fall. &lt;!-- Build a custom bundle at modernizr.com --&gt; &lt;script src="modernizr-custom.js"&gt;&lt;/script&gt; &lt;!-- Modernizr a

Example
<!-- Build a custom bundle at modernizr.com -->
<script src="modernizr-custom.js"></script>

<!-- Modernizr adds classes to <html> -->
<!-- <html class="webp flexbox cssanimations no-webgl"> -->
Quiz

Modernizr adds CSS classes to which HTML element?

Why is feature detection better than browser sniffing (User-Agent)?

Modernizr.load() with test/yep/nope is used for:

02Polyfills & Progressive EnhancementProgressive Enhancement with Modernizr /* Modernizr adds "no-webp" class when WebP is unsupported */ .hero { background-image: url(hero.webp); } .no-webp .hero { background-image: url(hero.jpg); } /* CSS Grid fallback */ .grid { display: grid; grid-tintermediate

Progressive Enhancement with Modernizr /* Modernizr adds "no-webp" class when WebP is unsupported */ .hero { background-image: url(hero.webp); } .no-webp .hero { background-image: url(hero.jpg); } /* CSS Grid fallback */ .grid { display: grid; grid-t

Example
/* Modernizr adds "no-webp" class when WebP is unsupported */
.hero { background-image: url(hero.webp); }
.no-webp .hero { background-image: url(hero.jpg); }

/* CSS Grid fallback */
.grid { display: grid; grid-template-columns: 1fr 1fr 1fr; }
.no-cssgrid .grid { display: flex; flex-wrap: wrap; }
Quiz

Progressive enhancement means:

The .no-webp CSS class is added by Modernizr when:

Modernizr.on("webp", fn) is for:

Track 04beginner

Polyfill.io / Polyfill library

Polyfill.io automatically detects the browser and serves only the polyfills it needs — making.

01Polyfills & Polyfill.ioWhat is a Polyfill? A polyfill is code that implements a feature that a browser doesn't natively support. Polyfill.io is. &lt;!-- Include in &lt;head&gt; before any other scripts --&gt; &lt;script src="https://polyfill.io/v3/polyfill.min.js"&gt;&lt;/beginner

What is a Polyfill? A polyfill is code that implements a feature that a browser doesn't natively support. Polyfill.io is. &lt;!-- Include in &lt;head&gt; before any other scripts --&gt; &lt;script src="https://polyfill.io/v3/polyfill.min.js"&gt;&lt;/

Example
<!-- Include in <head> before any other scripts -->
<script src="https://polyfill.io/v3/polyfill.min.js"></script>

<!-- Request specific features only -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=fetch,Promise,Array.prototype.flat"></script>

<!-- With flags -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=default,es2015,es2020"></script>
Quiz

What does Polyfill.io do differently from a static polyfill file?

A polyfill is:

Which features=value gets all default recommended polyfills?

02Writing Your Own PolyfillsWriting and Testing Polyfills // Always check first before polyfilling if (!Array.prototype.includes) { Array.prototype.includes = function(searchElement, fromIndex) { if (this == null) throw new TypeError(); const arr = Object(this); const len = arrintermediate

Writing and Testing Polyfills // Always check first before polyfilling if (!Array.prototype.includes) { Array.prototype.includes = function(searchElement, fromIndex) { if (this == null) throw new TypeError(); const arr = Object(this); const len = arr

Example
// Always check first before polyfilling
if (!Array.prototype.includes) {
  Array.prototype.includes = function(searchElement, fromIndex) {
    if (this == null) throw new TypeError();
    const arr = Object(this);
    const len = arr.length >>> 0;
    if (!len) return false;
    let i = Math.max(fromIndex|0, 0);
    while (i < len) {
      if (arr[i] === searchElement ||
         (searchElement !== searchElement && arr[i] !== arr[i])) {
        return true;
      }
      i++;
    }
    return false;
  };
}
Quiz

When should you polyfill a method?

Why check for existence before polyfilling?

Object.defineProperty is preferred over direct assignment in polyfills because:

Track 05beginner

JS Cookie

A simple, lightweight JavaScript API for handling cookies. Works in all browsers with a.

01Cookies & JS CookieCookies & JS Cookie Library Cookies are small text files stored in the browser. JS Cookie provides a clean API over. &lt;script src="https://cdn.jsdelivr.net/npm/js-cookie@3/dist/js.cookie.min.js"&gt;&lt;/script&gt; // or: npm install js-cookiebeginner

Cookies & JS Cookie Library Cookies are small text files stored in the browser. JS Cookie provides a clean API over. &lt;script src="https://cdn.jsdelivr.net/npm/js-cookie@3/dist/js.cookie.min.js"&gt;&lt;/script&gt; // or: npm install js-cookie

Example
<script src="https://cdn.jsdelivr.net/npm/js-cookie@3/dist/js.cookie.min.js"></script>
// or: npm install js-cookie
Quiz

Cookies.set("x", "val", { expires: 7 }) means the cookie:

Cookies.get() with no arguments returns:

What is the raw browser cookie API that JS Cookie wraps?

02Cookie Options & SecurityCookie Options & Security Cookies.set('secure-data', 'value', { expires: 7, // days until expiry (Date also accepted) path: '/', // available on all paths domain: '.example.com', // available on subdomains secure: true, // HTTPS only sameSite: 'stricintermediate

Cookie Options & Security Cookies.set('secure-data', 'value', { expires: 7, // days until expiry (Date also accepted) path: '/', // available on all paths domain: '.example.com', // available on subdomains secure: true, // HTTPS only sameSite: 'stric

Example
Cookies.set('secure-data', 'value', {
  expires:  7,         // days until expiry (Date also accepted)
  path:     '/',       // available on all paths
  domain:   '.example.com',  // available on subdomains
  secure:   true,      // HTTPS only
  sameSite: 'strict'   // 'strict', 'lax', 'none'
});
Quiz

Which cookie attribute prevents JavaScript from reading the cookie?

SameSite:"strict" cookie prevents:

Which storage type is automatically sent with every HTTP request to the server?

Track 06beginner

Axios (HTTP client)

Promise-based HTTP client for the browser and Node.js. Axios provides a clean API for.

01Axios Introduction & GETAxios HTTP Client Axios is one of the most popular HTTP libraries. It works in both browsers and Node.js. npm install axios import axios from 'axios';beginner

Axios HTTP Client Axios is one of the most popular HTTP libraries. It works in both browsers and Node.js. npm install axios import axios from 'axios';

Example
type User = { id: number; name: string };
const res = await axios.get<User[]>("/api/users");
Quiz

Unlike fetch, Axios automatically:

axios.get("/api", { params:{page:1} }) sends:

Where is the response data in an Axios response?

02POST, PUT, DELETE & ConfigAxios CRUD Methods All HTTP Methods // POST — create const { data } = await axios.post('/api/users', { name: 'Alice', email: 'alice@example.com' }); // PUT — full update await axios.put(`/api/users/${id}`, { name: 'Alice', email: 'new@ex.com' }); // beginner

Axios CRUD Methods All HTTP Methods // POST — create const { data } = await axios.post('/api/users', { name: 'Alice', email: 'alice@example.com' }); // PUT — full update await axios.put(`/api/users/${id}`, { name: 'Alice', email: 'new@ex.com' }); //

Example
// POST — create
const { data } = await axios.post('/api/users', {
  name: 'Alice', email: 'alice@example.com'
});

// PUT — full update
await axios.put(`/api/users/${id}`, { name: 'Alice', email: 'new@ex.com' });

// PATCH — partial update
await axios.patch(`/api/users/${id}`, { email: 'new@ex.com' });

// DELETE
await axios.delete(`/api/users/${id}`);

// HEAD, OPTIONS
await axios.head('/api/users');
await axios.options('/api/users');
Quiz

Which method should you use for a partial update (only some fields)?

axios.create() is used to:

What HTTP status does a successful POST/create typically return?

03Interceptors & Error HandlingAxios Interceptors & Error Handling Request Interceptors // Add auth token to every request axios.interceptors.request.use( (config) => { config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`; config.headers['X-Request-Time'] = Datintermediate

Axios Interceptors & Error Handling Request Interceptors // Add auth token to every request axios.interceptors.request.use( (config) => { config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`; config.headers['X-Request-Time'] = Dat

Example
// Add auth token to every request
axios.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
    config.headers['X-Request-Time'] = Date.now();
    return config;
  },
  (error) => Promise.reject(error)
);

// Log all outgoing requests
axios.interceptors.request.use(config => {
  console.log(`→ ${config.method.toUpperCase()} ${config.url}`);
  return config;
});
Quiz

What is a request interceptor used for?

In Axios error handling, error.response means:

How do you cancel an Axios request?

Track 07beginner

Moment.js (dates)

The original JavaScript date library. While now in maintenance mode (prefer Day.js), Moment.js is.

01Moment.js Parsing & FormattingMoment.js Moment.js simplifies date parsing, validation, manipulation, and formatting. Note: Moment.js is now in maintenance mode —. const now = moment(); // current time const date = moment('2024-03-15'); // from string const d2 = moment('03/15/2024beginner

Moment.js Moment.js simplifies date parsing, validation, manipulation, and formatting. Note: Moment.js is now in maintenance mode —. const now = moment(); // current time const date = moment('2024-03-15'); // from string const d2 = moment('03/15/2024

Example
const now  = moment();              // current time
const date = moment('2024-03-15');  // from string
const d2   = moment('03/15/2024', 'MM/DD/YYYY');
const ts   = moment(1710432000000); // from Unix timestamp
const iso  = moment('2024-03-15T10:30:00Z');
Quiz

moment().fromNow() returns:

Why is Moment.js in maintenance mode?

moment("2024-03-15").add(1,"month").format("YYYY-MM-DD") returns:

02Duration, Diff & TimezoneMoment Duration, Diff & moment-timezone const a = moment('2024-01-01'); const b = moment('2024-12-31'); b.diff(a, 'days'); // 365 b.diff(a, 'months'); // 11 b.diff(a, 'weeks'); // 52 b.diff(a, 'hours'); // 8760intermediate

Moment Duration, Diff & moment-timezone const a = moment('2024-01-01'); const b = moment('2024-12-31'); b.diff(a, 'days'); // 365 b.diff(a, 'months'); // 11 b.diff(a, 'weeks'); // 52 b.diff(a, 'hours'); // 8760

Example
const a = moment('2024-01-01');
const b = moment('2024-12-31');

b.diff(a, 'days');    // 365
b.diff(a, 'months');  // 11
b.diff(a, 'weeks');   // 52
b.diff(a, 'hours');   // 8760
Quiz

b.diff(a, "days") returns:

moment.duration(90,"minutes").asHours() returns:

What library extends Moment.js with timezone support?

Track 08beginner

Day.js (lightweight dates)

Day.js is a 2KB immutable date library — a Moment.js-compatible API that is much.

01Day.js IntroductionDay.js — Modern Date Library Day.js has a Moment.js-compatible API but is only 2KB (vs Moment's 67KB). It's immutable — all. npm install dayjs import dayjs from 'dayjs';beginner

Day.js — Modern Date Library Day.js has a Moment.js-compatible API but is only 2KB (vs Moment's 67KB). It's immutable — all. npm install dayjs import dayjs from 'dayjs';

Example
npm install dayjs
import dayjs from 'dayjs';
Quiz

Day.js main advantage over Moment.js is:

Day.js is immutable means:

Day.js plugins are tree-shakeable. This means:

02Day.js Plugins & LocalesDay.js Plugins & Locale import relativeTime from 'dayjs/plugin/relativeTime'; import duration from 'dayjs/plugin/duration'; import weekday from 'dayjs/plugin/weekday'; import isBetween from 'dayjs/plugin/isBetween'; import customParseFormat from 'dayintermediate

Day.js Plugins & Locale import relativeTime from 'dayjs/plugin/relativeTime'; import duration from 'dayjs/plugin/duration'; import weekday from 'dayjs/plugin/weekday'; import isBetween from 'dayjs/plugin/isBetween'; import customParseFormat from 'day

Example
import relativeTime from 'dayjs/plugin/relativeTime';
import duration     from 'dayjs/plugin/duration';
import weekday     from 'dayjs/plugin/weekday';
import isBetween   from 'dayjs/plugin/isBetween';
import customParseFormat from 'dayjs/plugin/customParseFormat';

dayjs.extend(relativeTime);
dayjs.extend(duration);
dayjs.extend(isBetween);

dayjs('2024-01-01').fromNow();           // '3 months ago'
dayjs('2024-01-01').to('2024-12-31');    // 'in 11 months'
dayjs.duration(90, 'minutes').asHours(); // 1.5
dayjs('2024-06-15').isBetween('2024-01-01','2024-12-31'); // true
Quiz

dayjs().isBetween("2024-01-01","2025-01-01") requires which plugin?

dayjs().locale("fr").format("dddd") returns:

What Day.js plugin gives you fromNow() / from() / to() relative time methods?

Track 09beginner

UUID.js

Generate universally unique identifiers (UUIDs) in JavaScript. The uuid package provides RFC 4122-compliant UUID.

01UUIDs & UUID GenerationWhat is a UUID? A UUID (Universally Unique Identifier) is a 128-bit value, formatted as 32 hex digits in 5. v1 — Time-based. Includes MAC address and timestamp. Unique. v4 — Random. Most common. No sequential info. Best. npm install uuid import { v4 beginner

What is a UUID? A UUID (Universally Unique Identifier) is a 128-bit value, formatted as 32 hex digits in 5. v1 — Time-based. Includes MAC address and timestamp. Unique. v4 — Random. Most common. No sequential info. Best. npm install uuid import { v4

Example
npm install uuid
import { v4 as uuidv4, v5 as uuidv5, validate, version } from 'uuid';

const id = uuidv4();       // 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
validate(id);              // true
version(id);               // 4

// v5: deterministic from namespace + name
const DNS_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
const id5 = uuidv5('hello.example.com', DNS_NAMESPACE);
uuidv5('hello.example.com', DNS_NAMESPACE) === id5; // always true
Quiz

Which UUID version is most commonly used for random IDs?

UUID v5 is useful because:

What is crypto.randomUUID()?

02UUID Use CasesUUID in Practice // With UUID primary keys, IDs never clash across distributed systems const user = { id: uuidv4(), name: 'Alice', created: Date.now() }; // PostgreSQL with UUID // CREATE TABLE users (id UUID DEFAULT gen_random_uuid() PRIMARY KEY); /intermediate

UUID in Practice // With UUID primary keys, IDs never clash across distributed systems const user = { id: uuidv4(), name: 'Alice', created: Date.now() }; // PostgreSQL with UUID // CREATE TABLE users (id UUID DEFAULT gen_random_uuid() PRIMARY KEY); /

Example
// With UUID primary keys, IDs never clash across distributed systems
const user = { id: uuidv4(), name: 'Alice', created: Date.now() };

// PostgreSQL with UUID
// CREATE TABLE users (id UUID DEFAULT gen_random_uuid() PRIMARY KEY);

// Pros: no sequential ID guessing, merge DBs without conflicts
// Cons: 16 bytes vs 4 bytes for integer ID, slightly slower indexing
// → Use UUID v7 for better DB index performance (time-ordered)
Quiz

Why use UUID for database primary keys instead of sequential integers?

An idempotency key is used to:

UUID v7 is better for databases compared to v4 because: