Skip to content

Archive / page 93

All articles

Every practical article from the Nalar archive, newest first.

JavaScript Updated 07 Sep 2025 1 min read

JavaScript Nullish Coalescing Operator (`??`)

The nullish coalescing operator, ??, provides a fallback only when the left-hand value is null or undefined. const username = null; const name = username ?? 'Guest'; console.log(name); // Guest ?? vs. || || falls back for every falsy value. ?? preserves valid falsy data such as 0, false, and '':

JavaScript Updated 07 Sep 2025 2 min read

JavaScript BigInt: Handling Large Integers

JavaScript Number can represent integers exactly only up to Number.MAX_SAFE_INTEGER (2^53 - 1). When you need larger integer values without losing precision, use BigInt. Create a BigInt const a = 123456789012345678901234567890n; const b = BigInt('123456789012345678901234567890'); The n suffix creates a BigInt literal. BigInt() is useful when converting a string or an integer-valued Number.

JavaScript Updated 02 Sep 2025 1 min read

JavaScript `||=`: Logical OR Assignment

The logical OR assignment operator, ||=, assigns a new value only when the current left-hand value is falsy. let name = ''; name ||= 'Guest'; console.log(name); // 'Guest' Falsy values include false, 0, -0, 0n, '', null, undefined, and NaN.

JavaScript Updated 02 Sep 2025 1 min read

JavaScript `&&=`: Logical AND Assignment

The logical AND assignment operator, &&=, assigns a new value to its left-hand operand only when the current value is truthy. Basic Syntax variable &&= newValue; Conceptually, this is similar to:

JavaScript Updated 07 Sep 2025 1 min read

JavaScript `??=`: Nullish Coalescing Assignment

The nullish coalescing assignment operator, ??=, assigns a value only when the current left-hand value is null or undefined. let name = null; name ??= 'Guest'; console.log(name); // Guest Function Defaults function greet(user) { user ??= 'Stranger'; console.log(`Hello, ${user}!`); } A default parameter may be even clearer when only undefined needs a fallback:

JavaScript Updated 02 Sep 2025 1 min read

Handle Multiple Promises with `Promise.allSettled()`

Promise.allSettled() waits until every input promise has either fulfilled or rejected, then returns the outcome of each operation. Unlike Promise.all(), one rejection does not stop you from receiving the other results. const tasks = [ Promise.resolve('first result'), Promise.reject(new Error('second failed')), Promise.resolve('third result'), ]; const results = await Promise.allSettled(tasks); for (const result of results) { if (result.status === 'fulfilled') { console.log('Value:', result.value); } else { console.error('Error:', result.reason); } } Each result has one of these shapes:

JavaScript Updated 02 Sep 2025 1 min read

Get Every RegExp Match with `String.matchAll()`

String.prototype.matchAll() returns an iterator containing every match of a global regular expression, including capturing groups and match indexes. const text = 'Order #123, Order #456, Order #789'; const regex = /Order #(\d+)/g; for (const match of text.matchAll(regex)) { console.log(match[0], match[1], match.index); } Named Capturing Groups const text = 'John: 123, Jane: 456'; const regex = /(?<name>\w+): (?<number>\d+)/g; for (const match of text.matchAll(regex)) { console.log(match.groups.name, match.groups.number); } Convert the Iterator to an Array const matches = [...'cat bat mat'.matchAll(/\b(\w+)at\b/g)]; This is convenient when you need map, filter, or other array operations, but iterating directly avoids storing all matches at once.

JavaScript Updated 02 Sep 2025 1 min read

Access JavaScript Array Elements with `at()`

Array.prototype.at() returns the element at a given integer index. Its main advantage over bracket notation is support for negative indexes. Positive Indexes const fruits = ['apple', 'banana', 'cherry']; console.log(fruits.at(0)); // 'apple' console.log(fruits.at(1)); // 'banana' Negative Indexes console.log(fruits.at(-1)); // 'cherry' console.log(fruits.at(-2)); // 'banana' Without at(), the traditional equivalent for the last element is:

JavaScript Updated 07 Sep 2025 1 min read

Update JavaScript Arrays Immutably with `with()`

Array.prototype.with() returns a copy of an array with one element replaced. The source array is left unchanged. const colors = ['red', 'blue', 'green', 'yellow']; const updated = colors.with(1, 'purple'); console.log(updated); // ['red', 'purple', 'green', 'yellow'] console.log(colors); // ['red', 'blue', 'green', 'yellow'] Negative Indexes Like at(), with() accepts negative indexes:

JavaScript Updated 02 Sep 2025 2 min read

Understanding Variable Scope in JavaScript

Variable scope determines where a name can be accessed. JavaScript uses lexical scope, with important differences between var, let, and const. Global Scope A binding declared at the top level can be visible throughout its module or script: const globalValue = 'global'; function showValue() { console.log(globalValue); } In modern ES modules, top-level declarations do not automatically become properties of window.

JavaScript Updated 02 Sep 2025 1 min read

Understanding `for`, `forEach`, and `map` in JavaScript

JavaScript offers several ways to iterate over arrays. for, forEach, and map overlap in what they can express, but each communicates a different intent. Traditional for const numbers = [1, 2, 3, 4, 5]; for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } Use a for loop when you need explicit index control, break, continue, unusual step sizes, or tight control over the iteration process.

JavaScript Updated 07 Sep 2025 2 min read

Sort JavaScript Arrays Immutably with `toSorted()`

toSorted() returns a sorted copy of an array without modifying the original. It is the non-mutating counterpart to sort(). Basic Usage For numbers, provide a comparator because the default sort order is based on strings: const numbers = [5, 3, 8, 1]; const sortedNumbers = numbers.toSorted((a, b) => a - b); console.log(sortedNumbers); // [1, 3, 5, 8] console.log(numbers); // [5, 3, 8, 1] Sort Objects const students = [ { name: 'Alice', grade: 85 }, { name: 'Bob', grade: 92 }, { name: 'Charlie', grade: 88 }, ]; const sortedByGrade = students.toSorted((a, b) => b.grade - a.grade); console.log(sortedByGrade); console.log(students); // unchanged Sort Strings with a Custom Rule const words = ['banana', 'apple', 'cherry']; const sortedWords = words.toSorted((a, b) => a.length - b.length); For locale-aware alphabetical ordering, use localeCompare:

JavaScript Updated 02 Sep 2025 1 min read

Reverse JavaScript Arrays Immutably with `toReversed()`

toReversed() returns a new array with the elements in reverse order while leaving the original array unchanged. It is the non-mutating counterpart to reverse(). Basic Usage const originalArray = [1, 2, 3, 4, 5]; const reversedArray = originalArray.toReversed(); console.log(reversedArray); // [5, 4, 3, 2, 1] console.log(originalArray); // [1, 2, 3, 4, 5] toReversed() vs. reverse() const a = [1, 2, 3]; const b = a.reverse(); console.log(a); // [3, 2, 1] console.log(b === a); // true reverse() changes the existing array. By contrast:

JavaScript Updated 07 Sep 2025 1 min read

Modify JavaScript Arrays Immutably with `toSpliced()`

toSpliced() creates a modified copy of an array without changing the source array. It is the non-mutating counterpart to splice(). Syntax array.toSpliced(start, deleteCount, ...items) start is the index where the change begins. deleteCount controls how many existing elements are removed. items are inserted at that position. Replace Elements const fruits = ['apple', 'banana', 'cherry', 'date']; const updated = fruits.toSpliced(1, 2, 'blueberry', 'fig'); console.log(updated); // ['apple', 'blueberry', 'fig', 'date'] console.log(fruits); // unchanged Insert Without Deleting const numbers = [1, 2, 5]; const result = numbers.toSpliced(2, 0, 3, 4); console.log(result); // [1, 2, 3, 4, 5] Remove Elements const values = ['a', 'b', 'c', 'd']; const result = values.toSpliced(1, 2); console.log(result); // ['a', 'd'] Why It Is Useful Non-mutating updates are especially helpful in UI state management, reducers, and code where several consumers share the same array reference. toSpliced() makes that intent explicit without manually combining slices.

JavaScript Updated 07 Sep 2025 2 min read

HTTP Requests in JavaScript with the Fetch API

The Fetch API is the built-in, promise-based HTTP client available in modern browsers and current JavaScript runtimes. It is a good default when you do not need a third-party request library. This guide uses DummyJSON to demonstrate common CRUD-style requests. Fetch All Products const response = await fetch('https://dummyjson.com/products'); if (!response.ok) throw new Error(`HTTP ${response.status}`); const data = await response.json(); console.log(data); Fetch a Product by ID const response = await fetch('https://dummyjson.com/products/1'); if (!response.ok) throw new Error(`HTTP ${response.status}`); console.log(await response.json()); Search Products Use URLSearchParams when query values are dynamic:

JavaScript Updated 02 Sep 2025 2 min read

HTTP Requests in JavaScript with Axios

Axios is a popular promise-based HTTP client for browsers and Node.js. It provides a compact API for requests, JSON handling, interceptors, timeouts, custom instances, and request cancellation. This guide uses the DummyJSON API to demonstrate common CRUD-style requests. 1. Install Axios With npm: npm install axios For a simple browser page, you can also load a CDN build:

JavaScript Updated 02 Sep 2025 1 min read

Group JavaScript Data with `Object.groupBy()`

Object.groupBy() groups iterable values by a key returned from a callback and produces an object whose properties contain arrays of matching items. Group Numbers const numbers = [1, 2, 3, 4, 5, 6]; const grouped = Object.groupBy(numbers, (number) => number % 2 === 0 ? 'even' : 'odd' ); The result has even and odd arrays.

JavaScript Updated 02 Sep 2025 2 min read

Group Data with JavaScript `Map.groupBy()`

Map.groupBy() groups iterable values into a Map. The callback determines the key for each group, and every map value is an array of matching elements. Basic Example const numbers = [1, 2, 3, 4, 5, 6]; const grouped = Map.groupBy(numbers, (number) => number % 2 === 0 ? 'even' : 'odd' ); console.log(grouped.get('even')); // [2, 4, 6] Group Objects const products = [ { name: 'Laptop', category: 'Electronics' }, { name: 'Shirt', category: 'Clothing' }, { name: 'Phone', category: 'Electronics' }, ]; const grouped = Map.groupBy(products, (product) => product.category); Arbitrary Map Keys The main advantage over Object.groupBy() is that map keys can be objects and other values without being converted to property keys:

JavaScript Updated 02 Sep 2025 2 min read

Format Dates in JavaScript

JavaScript provides several built-in ways to format dates. For user-facing text, Intl.DateTimeFormat is usually the best starting point because it understands locales and formatting options. toLocaleDateString() const date = new Date(); console.log(date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', })); Intl.DateTimeFormat Create a reusable formatter when formatting many values:

JavaScript Updated 02 Sep 2025 1 min read

Find the Last Matching Array Index with `findLastIndex()`

Array.prototype.findLastIndex() searches from the end of an array and returns the index of the first element, in reverse order, that matches a predicate. const numbers = [1, 3, 5, 8, 10, 12, 7, 6]; const index = numbers.findLastIndex((number) => number % 2 === 0); console.log(index); // 7 For object arrays:

JavaScript Updated 02 Sep 2025 1 min read

Find the Last Matching Array Element with `findLast()`

Array.prototype.findLast() searches an array from the end and returns the first element, in reverse order, that satisfies a predicate. const numbers = [1, 3, 5, 8, 10, 12, 7, 6]; const lastEven = numbers.findLast((number) => number % 2 === 0); console.log(lastEven); // 6 For objects:

JavaScript Updated 02 Sep 2025 2 min read

Arrow Functions vs Traditional Functions in JavaScript

JavaScript gives you several ways to define functions. Arrow functions are compact and capture lexical this, while traditional functions have their own this behavior and can be used as constructors. 1. Common Function Forms Function declaration: function greet(name) { return `Hello, ${name}!`; } Function expression:

Linux Updated 02 Sep 2025 2 min read

View and Manage Processes on Linux

A Linux process is a running instance of a program. Process-management tools help you inspect CPU and memory use, identify stuck applications, send signals, and manage foreground or background jobs. Inspect Processes with ps ps ps -e ps aux ps aux is a common BSD-style view that includes the owning user, PID, CPU, memory, and command.

Linux Updated 02 Sep 2025 2 min read

Mastering `curl` on Linux: Downloads and API Requests

curl is one of the most useful command-line tools for transferring data and testing HTTP APIs. It supports HTTP, HTTPS, FTP, and many other protocols, making it useful for downloads, automation, diagnostics, and API development. 1. Check or Install curl Check the installed version: curl --version On Debian or Ubuntu: