How to Exit a JavaScript Function

There are times when you need to quickly exit a JavaScript function while it’s executing. Fortunately, you can achieve this by using the return keyword. When JavaScript encounters the return keyword, it immediately exits the function. Any variable or value passed after return will be returned as the result. This technique is especially useful when you want to check for a certain condition within the function. For example, let’s say you expect a parameter to be present:...

How to extract the last segment from a path or URL using JavaScript

When working on a project, you may come across the need to extract the last segment from a path or URL. Whether it’s a filesystem path or a website URL, the following JavaScript code can help you achieve that: const lastItem = thePath.substring(thePath.lastIndexOf('/') + 1); To understand how this code works, let’s break it down: We define a thePath string that represents the path or URL, such as /Users/Flavio/Desktop. By calling lastIndexOf('/') on thePath, we find the index of the last occurrence of the forward slash (/) character....

How to Fix the \"__dirname is not defined in ES module scope\" Error

If you encounter the “__dirname is not defined in ES module scope” error while using __dirname in an ES module, here’s how you can fix it. In a Node script, __dirname is used to retrieve the path of the folder where the current JavaScript file resides. However, it cannot be used within an ES module, leading to the aforementioned error. To overcome this issue, follow these steps: Import the Node.js path module and the fileURLToPath function from the url module: import path from 'path'; import { fileURLToPath } from 'url'; Replicate the functionality of __dirname using the following code: const __filename = fileURLToPath(import....

How to Fix the `regeneratorRuntime is not defined` Error in Parcel

If you are using Babel in your project and you encounter the regeneratorRuntime is not defined error after adding an async function or any recent JavaScript feature, don’t worry. This issue can be resolved by loading the regenerator-runtime runtime in addition to the polyfill generated by Babel, which is used by Parcel. Here’s a solution you can try: add the following line at the top of your main JavaScript file:...

How to Fix the `TypeError: Attempted to Assign to Readonly Property` Error

If you’ve encountered the following error in your Next.js codebase or any JavaScript codebase: TypeError: Attempted to assign to readonly property Don’t worry! This error is not specific to Next.js and can occur in any JavaScript project. After some debugging, I discovered that the issue was related to a database column where I stored data as JSON. The problem arose when I tried to update this JSON object using dot syntax (e....

How to Flatten an Array in JavaScript: A Practical Guide

In JavaScript, flattening an array can be a common task. Fortunately, the ES2019 update introduced two new methods, flat and flatMap, to the Array prototype to simplify this process. However, it’s essential to note that these methods are only supported by more recent versions of browsers such as Firefox 62+, Chrome 69+, Edge 76+, and Safari 12+. If you need to support older browsers, you can consider using Babel to backport your code to a previous ECMAScript version....

How to Format a Date in JavaScript

Formatting dates in JavaScript is a common task. There are several methods available to generate a string representation of a date object. Let’s explore the different options: Given a Date object: const date = new Date('July 22, 2018 07:22:13'); The built-in methods provide various string representations: date.toString(); // "Sun Jul 22 2018 07:22:13 GMT+0200 (Central European Summer Time)" date.toTimeString(); // "07:22:13 GMT+0200 (Central European Summer Time)" date.toUTCString(); // "Sun, 22 Jul 2018 05:22:13 GMT" date....

How to Get the Current Timestamp in JavaScript

Discover the different methods JavaScript provides for generating the current UNIX timestamp. The UNIX timestamp is an integer that represents the number of seconds elapsed since January 1, 1970. On UNIX-like machines, such as Linux and macOS, you can easily find the UNIX timestamp by typing date +%s in the terminal: $ date +%s 1524379940 In JavaScript, the current timestamp can be obtained by calling the now() method on the Date object:...

How to Get the Index of an Iteration in a for-of Loop in JavaScript

In JavaScript, a for-of loop is a powerful feature introduced in ES6 that allows you to iterate over an array effortlessly. However, by default, it does not provide a straightforward way to access the index of each iteration. But worry not! In this blog post, I will show you how to easily obtain the index of an iteration using a combination of the destructuring syntax and the entries() method. Let’s dive in!...

How to Get the Month Name from a JavaScript Date

When working with a JavaScript Date object instance, you may sometimes need to extract the name of the month. This can be done easily using the toLocaleString() method, which is part of JavaScript’s internationalization methods. To obtain the month name in your current locale, you can follow these steps: Create a Date object: const today = new Date(); Use the toLocaleString() method with the month option set to 'long': today.toLocaleString('default', { month: 'long' }); This will return the full month name based on your current locale....