Skip to content

Topic archive

JavaScript

A versatile programming language for frontend and backend web development, supported by a broad ecosystem of runtimes, frameworks, libraries, and developer tools.

55 articles
JavaScript Updated 02 Sep 2025 1 min read

Truncate Text to a Maximum Length in JavaScript

User interfaces often need a shortened preview of longer text. A small helper can truncate a string to a maximum length and append an ellipsis when necessary. function limitText(text, limit) { if (typeof text !== 'string') return ''; if (!Number.isInteger(limit) || limit < 0) { throw new RangeError('limit must be a non-negative integer'); } if (text.length <= limit) return text; return `${text.slice(0, limit)}...`; } Examples:

JavaScript Updated 02 Sep 2025 1 min read

Extract a YouTube Video ID from a URL with JavaScript

YouTube links appear in several common formats, including youtube.com/watch?v=..., youtu.be/..., Shorts URLs, and embed URLs. A small JavaScript helper can normalize those formats and return the video ID. Use the URL API function getYouTubeVideoId(input) { const url = new URL(input); if (url.hostname === 'youtu.be') { return url.pathname.slice(1).split('/')[0] || null; } if (url.hostname.endsWith('youtube.com')) { if (url.pathname === '/watch') { return url.searchParams.get('v'); } const match = url.pathname.match(/^\/(?:embed|shorts|live)\/([^/?]+)/); return match?.[1] ?? null; } return null; } Examples console.log(getYouTubeVideoId('https://www.youtube.com/watch?v=QOM0xWASUwE')); console.log(getYouTubeVideoId('https://youtu.be/QOM0xWASUwE')); console.log(getYouTubeVideoId('https://www.youtube.com/embed/QOM0xWASUwE')); console.log(getYouTubeVideoId('https://www.youtube.com/shorts/QOM0xWASUwE')); Each returns:

JavaScript Updated 02 Sep 2025 2 min read

Remove Duplicates from JavaScript Arrays

Removing duplicates depends on what “duplicate” means for your data. Primitive values, objects with unique IDs, and records compared by several properties need different strategies. Primitive Values with Set const values = [1, 2, 3, 2, 4, 3]; const unique = [...new Set(values)]; console.log(unique); // [1, 2, 3, 4] Keep the First Object for Each ID const items = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 1, name: 'Alice again' }, ]; const seen = new Set(); const unique = items.filter((item) => { if (seen.has(item.id)) return false; seen.add(item.id); return true; }); Keep the Last Object for Each ID A Map naturally overwrites earlier values for the same key:

JavaScript Updated 07 Sep 2025 1 min read

Sort JavaScript Object Arrays by a Property Value

JavaScript comparator functions make it straightforward to sort arrays of objects by a numeric property. const data = [ { name: 'Edward', order: 21 }, { name: 'Sharpe', order: 37 }, { name: 'And', order: 45 }, { name: 'The', order: -12 }, { name: 'Magnetic', order: 13 }, { name: 'Zeros', order: 37 }, ]; Descending Order const sorted = data.toSorted((a, b) => b.order - a.order); This places the largest order value first.

JavaScript Updated 02 Sep 2025 1 min read

Find Text and Extract Context from a JavaScript String

Sometimes a search result is more useful when it includes nearby text instead of returning only an index. A small helper can find a substring and return a configurable amount of context around it. function findTextContext(text, query, context = 100) { const index = text.indexOf(query); if (index === -1) return null; const start = Math.max(0, index - context); const end = Math.min(text.length, index + query.length + context); return text.slice(start, end); } Example const text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor.'; const result = findTextContext(text, 'consectetur', 20); console.log(result); The helper finds the first occurrence and includes up to 20 characters before and after it.

JavaScript Updated 07 Sep 2025 2 min read

Filter JavaScript Arrays Quickly and Clearly

Array.prototype.filter() creates a new array containing only the elements that satisfy a predicate. It does not modify the original array. Filter by a Condition const values = [1, 2, 3, 4, 5, 6]; const even = values.filter((value) => value % 2 === 0); console.log(even); // [2, 4, 6] Filter Objects by a Property const users = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 25 }, ]; const age25 = users.filter((user) => user.age === 25); Remove Duplicates For primitive values, a Set is usually clearer than using filter() with indexOf:

JavaScript Updated 02 Sep 2025 2 min read

Manage Asynchronous Operations with Promises and Async/Await in JavaScript

Promises represent values that may become available later. async and await provide syntax for working with promises using control flow that resembles synchronous code. Create a Promise function callFirstName() { return new Promise((resolve) => { setTimeout(() => resolve('John'), 1000); }); } A promise can be fulfilled with resolve or rejected with reject.