Uncategorised

How to Fix the “structuredClone is not defined” Error in Node.js

The “structuredClone is not defined” error occurs when you try to use the structuredClone()/ method in JavaScript, but it’s not defined.

The "structuredClone is not defined" error occuring in a terminal.
The “structuredClone is not defined” error occuring in a terminal.

To fix it, install Node.js 17 or a newer version. Once you’ve updated Node.js, you can use structuredClone() to clone objects with all their properties and methods.

What causes the “structuredClone is not defined” error?

If you try to use the structuredClone() method in a script that’s running with a Node.js version lower than 17, you will encounter this error.

The structuredClone() method is used to create a deep copy of an object. It’s a built-in function in JavaScript and is used to clone an object with all its properties and methods.

But when the structuredClone() method is not defined, it means that the server environment doesn’t recognize the function and cannot perform the action.

Fix: update Node.js

To fix the “structuredClone is not defined” error in JavaScript, you need to install Node.js 17 or a newer version. If you’re using an older version of Node.js, it will throw an error when you try to use structuredClone().

Install from website

To download Node.js, visit the official website and opt for the LTS version, as it offers superior stability. As of the time of writing this article, the most recent LTS release of Node.js is v18.15.0.

The Node.js download page on the official website.
The Node.js download page on the official website.

Install with Chocolatey

If you’re using Chocolatey, Node.js is available as the nodejs package, meaning you can easily install it in a terminal using the following command.

Shell
# Use current LTS version choco install nodejs --version=18.5.0

After installing, you can use the structuredClone method to clone an object:

JavaScript
const obj = { name: 'Mike', friends: [{ name: 'Sam' }] }; const clonedObj = structuredClone(obj); console.log(obj.name === clonedObj); // false console.log(obj.friends === clonedObj.friends); // false

Key takeaways

If you get the “structuredClone is not defined” error when using the structuredClone() method in JavaScript, it means that the method is unavailable. To fix the problem, update your Node.js to a version newer than 17. You can get the latest version from the official Node.js website or install the nodejs package using Chocholatey.

How to Fix the “Unexpected reserved word (await)” Error in JavaScript

The “unexpected reserved word (await)” error occurs in JavaScript when you use the await keyword in a function that is not specified as async. To fix it, add an async modifier to the function to mark it as async.

The "Unexpected reserved word 'await'" error occurring in JavaScript.
The “Unexpected reserved word ‘await'” error occurring in JavaScript.

Here’s an example of the error occurring:

index.js
function getName() { // ❌ SyntaxError: Unexpected reserved word const str = await Promise.resolve('Coding Beauty'); return str; }

Note: As this is a syntax error, the function doesn’t need to be invoked for it to be detected, and no part of the code runs until it is resolved.

The async and await keywords work together in JavaScript (hence the commonly used term, async/await); to use the await keyword in a function, you must add the async modifier to the function to specify that it is an async function.

JavaScript
// ✅ Use "async" keyword modifier async function getName() { // ✅ Successful assignment - no error const str = await Promise.resolve('Coding Beauty'); return str; }

Fix “Unexpected reserved word (await)” error in nested function

If you’re using the await keyword, it’s likely that you already know that it has to be in an async function. What probably happened is that you nested functions and mistakenly ommited the async modifier from the innermost function containing the await keyword.

For example:

JavaScript
// ❌ SyntaxError: Unexpected reserved word export const createTask = async ({ description }) => // ❌ "async" keyword missing from innermost function (dispatch) => { await fetch('https://example.com/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ description }), }); dispatch({ type: 'taskCreated', description }); };

For await to work, the deepest function in the nesting hierarchy is required to be specified as async. It won’t work even if any or all of the outer functions are marked as async.

So we resolve the error in this case by adding the async modifier to the innermost function:

JavaScript
// ✅ No error export const createTask = async ({ description }) => // ✅ Innermost function marked as async async (dispatch) => { await fetch('https://example.com/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ description }), }); dispatch({ type: 'taskCreated', description }); };

In this example, we should be able to remove the async keyword from the outer function, as it isn’t performing any asynchronous operations with await, but this depends on whether the caller of createTask() is expecting it to return a Promise or not.

Here’s another example where this mistake frequently happens; using await in an array looping method:

JavaScript
// ❌ SyntaxError: Unexpected reserved word async function processPhotos(photoIds) { const data = await Promise.all(photoIds.map((photoId) => { const res = await fetch(`http://example.com/photos/${photoId}`); return await res.json(); })); // process data... }

Like in the previous example, the error occurs because the async keyword modifier is absent from the map() callback, even though it’s present in the function that calls map(). The fix is the same, add async to the map() callback.

JavaScript
// ✅ No error async function processPhotos(photoIds) { const data = await Promise.all( photoIds.map(async (photoId) => { const res = await fetch(`http://example.com/photos/${photoId}`); return await res.json(); }) ); // processing... }

Use await at top level

If you’re trying to use await at the top level of your file, you’ll need to set the type attribute to "module" in the script tag referencing the file in the HTML. This works when your code runs in browser environments.

For example:

index.html
<script type="module" src="index.js"></script>

Now you’ll be able to use await at the global scope in your file, e.g.:

index.js
console.log(await Promise.resolve('Coding Beauty'));

If you’re using Node.js, you’ll need to set the type attribute to "module" in your package.json file.

package.json
{ "name": "cb-js", "type": "module", "version": "1.0.0", "main": "index.js", "license": "MIT", // other fields... }

If there’s no package.json in your project directory, you can create one with the following command

Shell
# NPM npm init -y # Yarn yarn init -y

The await keyword will now work at the top level of your project files.

How to Convert Hours and Minutes to Seconds in JavaScript

To convert hours and minutes to seconds in JavaScript:

  1. Multiply the hours by 3600 to convert it to seconds.
  2. Multiply the minutes by 60 to convert it to seconds.
  3. Add these seconds to the seconds time value to get the total seconds.

For example:

JavaScript
function toSeconds(hours, minutes, seconds) { return hours * 3600 + minutes * 60 + seconds; } console.log(toSeconds(2, 15, 10)); // 8110 console.log(toSeconds(1, 5, 30)); // 3930

We create a reusable toSeconds() function to easily convert the hours and minutes to seconds.

The function is quite easy to understand; 1 hour equals 3600 seconds, so we multiply the hour value by 3600 to get the seconds equivalent. Similarly, 1 minute equals 60 seconds, so we multiply the minute value by 60 to get the seconds equivalent.

After this, we add the equivalent seconds values to the seconds argument to get the total seconds.

We could rewrite the function to accept the time values as named properties of an object, instead of as multiple parameters.

JavaScript
function toSeconds({ h: hours, m: minutes, s: seconds }) { return hours * 3600 + minutes * 60 + seconds; } console.log(toSeconds({ h: 2, m: 15, s: 10 })); // 8110 console.log(toSeconds({ h: 1, m: 5, s: 30 })); // 3930

This approach makes it easier to understand the role of each value passed to the function, a

Convert HH:mm:ss to seconds in JavaScript

Sometimes the time input to convert to seconds is a string in a time format, like HH:mm:ss. To convert to seconds in this case, we’ll separate the individual time values by the separator (: in this case), cast them each to numbers, and perform the same time conversion steps done in our previous examples.

For example:

JavaScript
function toSeconds(timeStr) { const [hours, minutes, seconds] = timeStr.split(':').map(Number); return hours * 3600 + minutes * 60 + seconds; } console.log(toSeconds('02:15:10')); // 8110 console.log(toSeconds('01:05:30')); // 3930

The input string here is in the HH:mm:ss format; the hour, minute, and second values are separated by a colon (:) and are each represented by a minimum of 2 digits.

The String split() method splits a string into an array of substrings separated by a given separator in the original string. We pass a colon as the separator to get an array of the individual time values.

JavaScript
const timeStr = '02:15:10'; console.log(timeStr.split(':')); // [ '02', '15', '10' ]

After getting this array, we use the map() method to transform each time value into a number. The map() method takes a callback and calls it on each element of an array and uses the result to populate a new array. For our scenario, the callback is simply the Number() constructor, so each time value in the array is converted to a number.

JavaScript
console.log(['02', '15', '10'].map(Number)); // [ 2, 15, 10 ]

Note

This:

JavaScript
const [hours, minutes, seconds] = timeStr.split(':').map(Number);

is equivalent to this:

JavaScript
const [hours, minutes, seconds] = timeStr .split(':') .map((str) => Number(str));

The second one is longer, but it makes it clear exactly what arguments are passed to the map() callback. In the first one, map() automatically passes 3 arguments to its callback, which could be problematic if the callback returns a different result depending on the number of arguments it receives, for instance, a parseInt() callback.

We then use a destructuring assignment to unpack the number array values into separate hour, minute, and second variables.

JavaScript
const [hour, minute, seconds] = [2, 15, 10]; console.log(hour); // 2 console.log(minute); // 15 console.log(seconds); // 10

After doing this, we perform the same multiplication and addition we did in the first example, to convert the hours and minutes to seconds and get the total seconds.

How to Get the Window’s Width and Height in React

To get the width and height of the window in React, access the window object’s innerWidth and innerHeight properties respectively.

App.js
import { useRef } from 'react'; export default function App() { const windowSize = useRef([window.innerWidth, window.innerHeight]); return ( <div> <h2>Width: {windowSize.current[0]}</h2> <h2>Height: {windowSize.current[1]}</h2> </div> ); } 
Displaying the width and height of the window.
Displaying the width and height of the window.

The innerWidth property returns the interior width of the window in pixels, including the width of the vertical scrollbar, if it is present.

Similarly, innerHeight property returns the interior height of the window in pixels, including the height of the horizontal scrollbar, if it is present.

Get window width and height on resize in React

In the previous example, we needed to get the window width and height only once and we used a ref to store it.

If instead, you want to get the window’s width and height when it is resized, you’ll need to add a resize event listener to the window object and create a state variable to track changes to the width and height.

App.js
import { useState, useEffect } from 'react'; export default function App() { const [windowSize, setWindowSize] = useState([ window.innerWidth, window.innerHeight, ]); useEffect(() => { const handleWindowResize = () => { setWindowSize([window.innerWidth, window.innerHeight]); }; window.addEventListener('resize', handleWindowResize); return () => { window.removeEventListener('resize', handleWindowResize); }; }); return ( <div> <h2>Width: {windowSize[0]}</h2> <h2>Height: {windowSize[1]}</h2> </div> ); }
The window’s width and height are updated when it is resized.

We use the useState React hook to create a state variable that will be updated whenever the height or width of the window changes.

The useState hook returns an array of two values. This first is a variable that stores the state, and the second is a function that updates the state when it is called.

The useEffect hook is used to perform an action when a component first renders, and when one or more specified dependencies change. In our example, the action is to add the event listener for the resize hook with the addEventListener() method.

We pass an empty dependencies array to the useEffect, so that it is called only once in the component’s lifetime, and the resize event listener is only registered once – when the component first renders.

App.js
useEffect(() => { const handleWindowResize = () => { setWindowSize([window.innerWidth, window.innerHeight]); }; window.addEventListener('resize', handleWindowResize); return () => { window.removeEventListener('resize', handleWindowResize); }; });

In the resize event listener, we update the state variable with the new height and width of the window.

The function we return in useEffect is a function that performs clean-up operations in the component. We use the removeEventListener() method to remove the resize event listener in this clean-up function and prevent a memory leak.

Note: useEffect‘s cleanup function runs after every re-render, not only when the component unmounts. This prevents memory leaks that happen when an observable prop changes value without the observers in the component unsubscribing from the previous observable value.

How to Easily Handle the onScroll Event in React

To handle the onScroll event on a React element, assign a function to the onScroll prop of the element and use the event object to perform an action. That action will occur whenever the user scrolls up or down on the page.

For example:

App.jsx

import { useState } from 'react';

export default function App() {
  const [scrollTop, setScrollTop] = useState(0);

  const handleScroll = (event) => {
    setScrollTop(event.currentTarget.scrollTop);
  };

  return (
    <div>
      Scroll top: <b>{scrollTop}</b>
      <br />
      <br />
      <div
        style={{
          border: '1px solid black',
          width: '400px',
          height: '200px',
          overflow: 'auto',
        }}
        onScroll={handleScroll}
      >
        {[...Array(10)].map((_, i) => (
          <p key={i}>Content</p>
        ))}
      </div>
    </div>
  );
}
The text is updated when the component's onScroll event fires.
The text is updated when the component’s onScroll event fires.

The function (event listener) passed to the onScroll prop is invoked whenever the viewport is scrolled. It is called with an event object, which you can use to perform actions and access information related to the scroll event.

The currentTarget property of this event object returns the element that the onScroll listener was attached to.

Tip: If you’re not sure of when to use the event object’s currentTarget or target properties, this article might help: Event target vs currentTarget in JavaScript: The Important Difference.

We use the element’s scrollTop property to get how far the element’s scrollbar is from its topmost position. Then we update the state variable with the new value, and this reflects on the page.

Note: We used the useState hook to manage the state. This hook returns an array of two values, where the first is a variable that stores the state, and the second is a function that updates the state when it is called.

Handle onScroll event on window object in React

We can also handle the onScroll event on the global window object, to perform an action when the viewport is scrolled. We can do this with the addEventListener() method:

App.js

import { useState, useEffect } from 'react';

export default function App() {
  const [scrollTop, setScrollTop] = useState(0);

  useEffect(() => {
    const handleScroll = (event) => {
      setScrollTop(window.scrollY);
    };

    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return (
    <div>
      <div
        style={{
          position: 'fixed',
          padding: '10px 0',
          top: '0',
          backgroundColor: 'white',
          borderBottom: '1px solid #c0c0c0',
          width: '100%',
        }}
      >
        Scroll top: <b>{scrollTop}</b>
      </div>
      <div style={{ marginTop: '50px' }}>
        {[...Array(30)].map((_, i) => (
          <p key={i}>Content</p>
        ))}
      </div>
    </div>
  );
}
The text is updated when the window's onScroll event fires.
The text is updated when the window’s onScroll event fires.

The addEventListener() method takes up to two arguments:

  1. type: a string representing the event type to listen for.
  2. listener: the function called when the event fires.

It also takes some optional arguments, which you can learn more about here.

We call addEventListener() in the useEffect hook to register the listener once the component renders as the page loads. We pass an empty dependencies array to useEffect so this registration happens only once. In the cleanup function, we call the removeEventListener() method to unregister the event listener and prevent a memory leak.

In the onScroll listener, we access the Window scrollY property to display the number of pixels that the page has currently scrolled horizontally.

How to Capitalize the First Letter of Each Word in an Array in JavaScript

To capitalize the first letter of each word in an array in JavaScript:

  1. Iterate over the words array with .map().
  2. For each word, return a new word, the uppercased form of the word’s first letter added to the rest of the word.

For example:

function capitalizeWords(arr) {
  return arr.map((word) => {
    const capitalizedFirst = word.charAt(0).toUpperCase();
    const rest = word.slice(1).toLowerCase();
    return capitalizedFirst + rest;
  });
}

const words = ['welcome', 'to', 'CODING', 'Beauty'];

// [ 'Welcome', 'To', 'Coding', 'Beauty' ]
console.log(capitalizeWords(words));

Our capitalizeWords() function takes an array of words and returns a new array with all the words capitalized, without mutating the original array.

Firstly, we call the map() method on the array, passing a callback function as an argument. This function will be called and return a result for each word in the array.

In the callback, we get the word’s first character with charAt(), convert it to uppercase with toUpperCase(), and concatenate it with the rest of the string.

We use the String slice() method to get the remaining part of the string. Passing 1 to slice() makes it return the portion of the string from the second character to the end.

Note: String (and array) indexing is zero-based JavaScript, so the first character in a string is at index 0, the second at 1, and the last at str.length-1

After capitalizing the word, we lowercase it with the String toLowerCase() method. You can remove this toLowerCase() call if it’s not necessary for the non-first letter of each word in the array to be capitalized.

How to Use an Image as a Link in React

Related: How to Link an Image in React

To use an image as a link in React, wrap the image in an anchor (a) tag. Clicking an image link will make the browser navigate to the specified URL.

For example:

App.js

import cbLogo from './cb-logo.png';

export default function App() {
  return (
    <div>
      Click the logo to navigate to the site
      <br />
      <br />
      <a href="https://codingbeautydev.com" target="_blank" rel="noreferrer">
        <img src={cbLogo} alt="Coding Beauty logo"></img>
      </a>
    </div>
  );
}
The browser navigates to the URL when the image link is clicked.
The browser navigates to the URL when the image link is clicked.

We use an import statement to link the image into the file, and assign it to the src prop of the img element to display it.

The properties set on an a element will work as usual when it wraps an image. For instance, in the example, we set the a element’s target property to _blank, to open the URL in a new tab. Removing this will make it open in the same tab as normal.

We also set the rel prop to noreferrer for security purposes. It prevents the opened page from gaining access to any information about the page from which it was opened from.

For React Router, you can use an image as link by wrapping the image in a Link element.

For example:

ImagePages.jsx

import { Link } from 'react-router-dom';

export default function ImagesPage() {
  return (
    <div>
      <Link to="/nature" target="_blank" rel="noreferrer">
        <img src="/photos/tree-1.png" alt="Nature"></img>
      </Link>
    </div>
  );
}

How to Sort an Object Array by a Boolean Property in JavaScript

To sort an array of objects by a boolean property in JavaScript, call the sort() method on the array with a callback as an argument. In the function, use the boolean property to return an expression that evaluates to a positive number, a negative number, or zero. This will sort the array in place, by the boolean property, i.e.:

const trueFirst = users.sort((a, b) => b.boolProp - a.boolProp);

const falseFirst = users.sort((a, b) => a.boolProp - b.boolProp);

For example:

const users = [
  { name: 'Kate', premium: false },
  { name: 'Bob', premium: true },
  { name: 'Jeff', premium: false },
  { name: 'Samantha', premium: true },
];

const premiumFirst = users.sort((a, b) => b.premium - a.premium);

/*
  [
    { name: 'Bob', premium: true },
    { name: 'Samantha', premium: true },
    { name: 'Kate', premium: false },
    { name: 'Jeff', premium: false }
  ]
*/

console.log(premiumFirst);

const nonPremiumFirst = users.sort((a, b) => a.premium - b.premium);

/*
  [
    { name: 'Kate', premium: false },
    { name: 'Jeff', premium: false },
    { name: 'Bob', premium: true },
    { name: 'Samantha', premium: true }
  ]
*/

console.log(nonPremiumFirst);

The Array sort() method takes a callback function as an argument. It uses the value returned from this callback to determine the order in which to sort the values. For each item pair in the array, a and b:

If the returned value is negative, a is placed before b in the sorted array.

If the value is positive, b is placed before a.

If the value is 0, the order of a and b is not changed.

const arr = [5, 3, 8, 1, 7];

// Sort in ascending order
arr.sort((a, b) => a - b);

console.log(arr); // [ 1, 3, 5, 7, 8 ]

// Sort in descending order
const desc = arr.sort((a, b) => b - a);

console.log(desc); // [ 8, 7, 5, 3, 1 ]

Because we used the subtraction operator (-) on the boolean values, they are coerced to numbers before the subtraction happens. Truthy values are coerced to 1, and falsy values 0.

console.log(true + true); // 2

console.log(true + false); // 1

console.log(false + false); // 0

After seeing how the sort() method and boolean coercion works, it’s easy to understand the way the was sorted to place the objects with a boolean property value of true above the ones with false, and vice versa.

Sort object array by boolean property without mutation

The sort() method sorts the array in place, which means it gets modified. To prevent this, we can use the spread syntax (...) to create a shallow copy of the array for the sort:

const users = [
  { name: 'Kate', premium: false },
  { name: 'Bob', premium: true },
  { name: 'Jeff', premium: false },
  { name: 'Samantha', premium: true },
];

// 👇 Clone array with spread syntax
const premiumFirst = [...users].sort((a, b) => b.premium - a.premium);

/*
  [
    { name: 'Bob', premium: true },
    { name: 'Samantha', premium: true },
    { name: 'Kate', premium: false },
    { name: 'Jeff', premium: false }
  ]
*/

console.log(premiumFirst);

/*
  Original not modified:
  [
    { name: 'Kate', premium: false },
    { name: 'Bob', premium: true },
    { name: 'Jeff', premium: false },
    { name: 'Samantha', premium: true }
  ]
*/

console.log(users);

By avoiding mutations, we can make our code more readable, predictable, and modular.

How to Convert XML to JSON in Node.js

We can use the xml-js library from NPM to easily convert XML to JSON in Node.js, i.e.:

import { xml2json } from 'xml-js';

// ...

const json = xml2json(xml);

For example:

index.js

import { xml2json } from 'xml-js';
import fs from 'fs/promises';

// Read from file
// const xml = await fs.readFile('data.xml',  { encoding: 'utf-8' });

const xml = `<name>Garage</name>
<cars>
    <color>red</color>
    <maxSpeed>120</maxSpeed>
    <age>2</age>
</cars>
<cars>
    <color>blue</color>
    <maxSpeed>100</maxSpeed>
    <age>3</age>
</cars>
<cars>
    <color>green</color>
    <maxSpeed>130</maxSpeed>
    <age>2</age>
</cars>`;

const json = xmltojson(xml, );

console.log(json);

This code will have the following JSON output:

{"declaration":{"attributes":{"version":"1.0","encoding":"UTF-8"}},"elements":[{"type":"element","name":"languages","elements":[{"type":"element","name":"language","elements":[{"type":"text","text":"\n      English\n   "}]},{"type":"element","name":"language","elements":[{"type":"text","text":"\n      French\n   "}]},{"type":"element","name":"language","elements":[{"type":"text","text":"\n      Spanish\n   "}]}]}]}

What are XML and JSON?

Let’s go through these terms in case you’re not familiar with them

XML (eXtensible Markup Language) is a markup language similar to HTML that was designed to store and transport data. Unlike HTML, XML doesn’t have any predefined tags. Instead, we define our own tags according to our requirements.

Example of XML data:

<users>
   <user>
     <name>Jack</name>
   </user>
   <user>
     <name>Samantha</name>
   </user>
</users>

JSON (JavaScript Object Notation) is a text format used to store and transport data based on JavaScript object syntax and is commonly used to build RESTful APIs.

Example of JSON data:

{
  "users": [
    {
      "name": "Jack"
    },
    {
      "name": "Samantha"
    }
  ]
}

You saw more examples of XML and JSON data in the previous section.

Install xml-js

Before using xml-js, we need to install it in our Node.js project. We can do this with the NPM CLI.

npm i xml-js

# Yarn
yarn add xml-js

After installation, we’ll be able to import it into a JavaScript module, like this:

import { xml2json } from 'xml-js';

// CommonJS
const { xml2json } = require('xml-js');

We use import destructuring to access the xml2json() method directly from the library.

The xml2json() function

The xml2json() function has two parameters. The first is the XML string to convert to JSON, and the second is an optional object.

const json = xml2json(xml, { spaces: 2, compact: true });

Customize conversion of XML to JSON in Node.js

We use this object to specify various options for customizing the conversion process.

In our example, we don’t pass an object, so the default options are used. We can pass an object with a spaces option to properly format and indent the resulting JSON.

import { xml2json } from 'xml-js';

const xml = `<?xml version="1.0" encoding="UTF-8"?>
<languages>
   <language>
      English
   </language>
   <language>
      French
   </language>
   <language>
      Spanish
   </language>
</languages>`;

// 👇 Set "spaces" option
const json = xml2json(xml, { spaces: 2 });

console.log(json);

Here’s the new output:

{
  "declaration": {
    "attributes": {
      "version": "1.0",
      "encoding": "UTF-8"
    }
  },
  "elements": [
    {
      "type": "element",
      "name": "languages",
      "elements": [
        {
          "type": "element",
          "name": "language",
          "elements": [
            {
              "type": "text",
              "text": "\n      English\n   "
            }
          ]
        },
        {
          "type": "element",
          "name": "language",
          "elements": [
            {
              "type": "text",
              "text": "\n      French\n   "
            }
          ]
        },
        {
          "type": "element",
          "name": "language",
          "elements": [
            {
              "type": "text",
              "text": "\n      Spanish\n   "
            }
          ]
        }
      ]
    }
  ]
}

The compact property to determine whether the resulting JSON should be detailed or compact. It is false by default.

import { xml2json } from 'xml-js';

const xml = `<?xml version="1.0" encoding="UTF-8"?>
<languages>
   <language>
      English
   </language>
   <language>
      French
   </language>
   <language>
      Spanish
   </language>
</languages>`;

// 👇 Set "compact" option
const json = xml2json(xml, { spaces: 2, compact: true });

console.log(json);

Now the resulting JSON will have a significantly smaller size than before:

{
  "_declaration": {
    "_attributes": {
      "version": "1.0",
      "encoding": "UTF-8"
    }
  },
  "languages": {
    "language": [
      {
        "_text": "\n      English\n   "
      },
      {
        "_text": "\n      French\n   "
      },
      {
        "_text": "\n      Spanish\n   "
      }
    ]
  }
}

How to Remove All Classes From an Element With JavaScript

Related: How to Remove a Class From All Elements in JavaScript

To remove all classes from an element in JavaScript, set the className property of the element to an empty string (''), i.e., element.className = ''. Setting the className property to an empty string will eliminate every class in the element.

const box = document.getElementById('box');

// 👇 Remove all classes from element.
box.className = '';

For this HTML:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Coding Beauty Tutorial</title>
    <style>
      .class-1 {
        height: 30px;
        width: 300px;
        font-size: 1.1em;
        box-shadow: 0 2px 3px #c0c0c0;
      }

      .class-2 {
        background-color: blue;
        color: white;
        border: 1px solid black;
        border-radius: 3px;
      }
    </style>
  </head>
  <body>
    <input id="input" type="text" class="class-1 class-2" />
    <br /><br />
    <button id="btn">Remove classes</button>
    <script src="index.js"></script>
  </body>
</html>

This JavaScript code will remove all classes from the input field when the button is clicked:

index.js

const btn = document.getElementById('btn');

const input = document.getElementById('input');

btn.addEventListener('click', () => {
  input.className = '';
});
All classes from the input field are removed when the button is clicked.

The className property is used to get and set the value of the class attribute of a specified element.

Setting className to an empty string effectively removes all the classes from the element.

Remove all classes from element with removeAttribute() method

To remove all classes from an element with this approach, call the removeAttribute() method on the specified for the class attribute, i.e., element.removeAttribute('class'). This method will remove the class attribute from the element, effectively removing all the element’s classes.

const box = document.getElementById('box');

// 👇 Remove all classes from element
box.removeAttribute('class');

removeAttribute() takes a name and removes the attribute from an element with that name.

For this HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Coding Beauty Tutorial</title>
    <style>
      .class-1 {
        height: 30px;
        font-size: 1.1em;
        box-shadow: 0 2px 3px #c0c0c0;
      }

      .class-2 {
        background-image: linear-gradient(to bottom, rgb(136, 136, 255), blue);
        color: white;
        border: none;
      }
    </style>
  </head>
  <body>
    <button id="styled-btn" type="text" class="class-1 class-2">
      Download
    </button>
    <br /><br />
    <button id="btn">Remove classes</button>
    <script src="index.js"></script>
  </body>
</html>

This JavaScript code will remove all classes from the styled button when the other button is clicked.

const btn = document.getElementById('btn');

const styledButton = document.getElementById('styled-btn');

btn.addEventListener('click', () => {
  styledButton.removeAttribute('class');
});
All classes from removed from the button when the other button is clicked.

In the first method, the class attribute remains on the element after setting the className property. But using the removeAttribute() method completely removes the class attribute from the element.

If the element doesn’t have a class attribute, removeAttribute() will return without causing an error.

Either of these two methods is fine, it’s up to you which one to pick. I think using the className property is better because it more clearly shows what you’re trying to do.