tutorial

How to Fix the “Unknown file extension .ts” Error in ts-node

The “Unknown file extension .ts” error occurs in ts-node occurs when "type": "module" is set in your package.json file. To fix it, run the TypeScript file with ts-node --esm my-file.ts, or remove "type": "module" from your package.json file.

For example, in a project with this package.json file:

package.json
{ "name": "cb-js", "version": "1.0.0", "main": "index.js", "type": "module", "license": "MIT", "devDependencies": { "prettier": "^2.8.1" } }

If you have a TypeScript file in your project, e.g., my-file.ts:

my-file.ts
const num: number = 10; console.log(num ** 2);

Running the ts-node index.ts command will result in the ERR_UNKNOWN_FILE_EXTENSION TypeError in ts-node:

The ERR_UNKNOWN_FILE_EXTENSION TypeError occurs.
The ERR_UNKNOWN_FILE_EXTENSION TypeError occurs.

To fix the “Unknown file extension ‘.ts'” error in ts-node, run ts-node with the --esm option set:

Shell
ts-node --esm my-file.ts # Or ts-node-esm my-file.ts # Or node --loader ts-node/esm my-file.ts
Running ts-node in esm mode.
Running ts-node in esm mode.

To avoid using the --esm flag, add the following to your tsconfig.json file:

tsconfig.json
{ // other settings... "ts-node": { "esm": true, "experimentalSpecifierResolution": "node" } }

After doing this, you’ll be able to run the TypeScript file with only ts-node:

Shell
ts-node my-file.ts
Running the TypeScript file with only ts-node.
Running the TypeScript file with only ts-node.

You may also need to add one or more of the following options to your tsconfig.json file:

tsconfig.json
{ // other settings.. "compilerOptions": { // other compiler options... "esModuleInterop": true, "module": "ESNext", // "module": "CommonJS" should work too "moduleResolution": "Node" }, "include": ["/**/*.ts"], "exclude": ["node_modules"] }

Remove "type": "module" from tsconfig.json file

Alternatively, instead of doing all of the above, you can simply remove the "type": "module" field from your package.json file to fix the ERR_UNKNOWN_FILE_EXTENSION error in ts-node.

tsconfig.json
{ "name": "cb-js", "version": "1.0.0", "main": "index.js", // removed: "type": "module", "license": "MIT", "devDependencies": { "prettier": "^2.8.1" } }

And you’ll be able to run the TypeScript file with ts-node successfully.

Compile TypeScript files into JavaScript

Another way to avoid ERR_UNKNOWN_FILE_EXTENSION is to stop using ts-node altogether. Instead, you can compile your TypeScript files with tsc and run the JavaScript output with node – the classic way.

Shell
# Compile with tsc npx tsc --outDir dist my-file.ts # Run with node node dist/my-file.ts

Basic TypeScript compilation setup

Here’s a great way to set up your project for easily compiling and debugging TypeScript files.

First, install the TypeScript compiler:

Shell
npm i tsc

Then specify the src dir and out dir in tsconfig.json, and enable source maps for seamless Typescript debugging:

tsconfig.json
{ "compilerOptions": { // ... other options "rootDir": "src", // Location of TypeScript files "outDir": "dist", // Location of compiled JavaScript files "sourceMap": true // Generate sourcemaps } }

Finally, create a start NPM script that automatically runs the tsc and node commands one after the other:

JavaScript
{ // ... other options "scripts": { "start": "tsc && node index.js" } }

Now you can run the script easily with npm start.

And you can debug TypeScript in VSCode too.

How to Get an Object Value By Key in TypeScript

You can easily get an object’s value by a key in Typescript using bracket notation, i.e., obj['key'], obj[myVar], etc. If the key exists, you will get the corresponding value back.

For example:

TypeScript
type Car = { name: string; maxSpeed: number; color: string; }; const car: Car = { name: 'CB Flash', maxSpeed: 200, color: 'blue', }; console.log(car['name']); // CB Flash // Dot notation console.log(car.name); // CB Flash // Get value by variable key const prop = 'name'; console.log(car[prop]); // CB Flash // Computed property key const val = car[3 > 1 ? 'name' : 'maxSpeed'] console.log(val) // CB Flash

Dot notation property access

There are two ways to get an object’s value by a property key in TypeScript: dot notation and bracket notation.

In dot notation, we access an object value with the obj.propKey syntax.

TypeScript
type Car = { name: string; maxSpeed: number; color: string; }; const car = { name: 'CB Flash', maxSpeed: 200, color: 'blue', }; console.log(car.name); // CB Flash console.log(car.maxSpeed); // 200 console.log(car.color); // blue

With the obj.propKey syntax, the propKey must be a valid TypeScript identifier. Otherwise, a syntax error will be thrown:

TypeScript
type Car = { [propKey: string]: string }; const car: Car = {}; car.100 = 'go faster'; // ❌ SyntaxError console.log(car.100); // ❌ SyntaxError

propKey can also be a reserved keyword, like let, var, async, etc.

TypeScript
type Car = { [propKey: string]: string }; const car: Car = {}; car.let = 'works'; car.await = 'works too'; console.log(car.let); // works console.log(car.await); // works too

Bracket notation property access

In bracket notation, we access the property value with the obj[expression] syntax. The expression should evaluate to a string or Symbol that represent the property’s key.

TypeScript
type Car = { name: string; maxSpeed: number; color: string; }; const car: Car = { name: 'CB Flash', maxSpeed: 200, color: 'blue', }; console.log(car['name']); // CB Flash console.log(car['maxSpeed']); // 200 console.log(car['color']); // blue

Unlike dot notation, with bracket notation, we can access keys that are not valid TypeScript identifiers, like numbers and keys containing spaces.

TypeScript
type Car = { [propKey: string]: string }; const car: Car = {}; car['100'] = 'go faster'; car['year produced'] = 2022; console.log(car['100']); // go faster console.log(car['year produced']); // 2022

Computed property names

The expression we put in-between the brackets can be as complex as possible, as long it evaluates to a string or Symbol.

For example, we can put a ternary expression in-between the brackets:

TypeScript
type Car = { name: string; maxSpeed: number; color: string; }; const car: Car = { name: 'CB Flash', maxSpeed: 200, color: 'blue', }; const num = 3; const val = car[num > 1 ? 'name' : 'maxSpeed']; console.log(val); // CB Flash

Note: If the expression to the left of the ? is truthy, the ternary operator returns the value to the left. Otherwise, it returns the value to the right.

The ternary expression evaluates to the 'name' key, so the corresponding property value is returned.

You can also this computed property names approach to set a new property on a object.

TypeScript
type Car = { [propKey: string]: string | number; }; const car: Car = {}; const num = 7; car[num > 10 ? 'name' : 'maxSpeed'] = 500; console.log(car['name']); // undefined console.log(car['maxSpeed']); // 500

How to Get the Current Year in Vue.js

To get the current year in Vue.js, create a new Date object with the Date() constructor, then use the getFullYear() method to get the year of the Date. getFullYear() will return a number that represents the current year.

For example:

App.vue
<template> <div> {{ new Date().getFullYear() }} <div> &copy; {{ new Date().getFullYear() }} Coding Beauty </div> </div> </template>
The current year is displayed.
The current year is displayed.

We use the Date() constructor to create a new Date object. When Date() is called with no arguments, the Date object is created using the current date and time.

The Date getFullYear() method returns a number that represents the year of the Date. Since the Date object here stores the current date, getFullYear() returns the current year.

Get current year with data property

We can also put the current year in a data variable instead of placing it directly in the template with the {{ }} symbols. This allows us to more easily reuse the value in multiple places in the template markup.

App.vue
<template> <div> {{ currYear }} <div>&copy; {{ currYear }} Coding Beauty</div> </div> </template> <script> export default { data() { return { currYear: new Date().getFullYear(), }; }, }; </script>

Get current year with Composition API

Of course, this also works when using the Vue 3 Composition API:

App.vue
<script setup> const currYear = new Date().getFullYear(); </script> <template> <div> {{ currYear }} <div>&copy; {{ currYear }} Coding Beauty</div> </div> </template>

Get current month

If you also want to get the current month, the getMonth() method is for you.

getMonth() returns a zero-based index that represents the month of the Date. Zero-based here means that 0 = January, 1 = February, 2 = March, etc.

App.vue
<template> <div>Month number {{ currMonth }} in {{ currYear }}</div> </template> <script> export default { data() { return { currMonth: new Date().getMonth(), currYear: new Date().getFullYear(), }; }, }; </script>
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getmonth
The month number is displayed.

If you want the month name directly (the more likely case), the Date toLocaleString() method will do the job.

App.vue
<template> <div>{{ currMonth }} in {{ currYear }}</div> </template> <script> export default { data() { return { currMonth: new Date().toLocaleString([], { month: 'long', }), currYear: new Date().getFullYear(), }; }, }; </script>
The month name is displayed.

Check out this article for a full guide on how to convert a month number to its equivalent month name in JavaScript.

Get current day of month

Similarly, to get the current day in the month, you’d use the Date getDate() method:

App.vue
<template> <div>{{ currMonth }} {{ currDay }}, {{ currYear }}</div> </template> <script> export default { data() { return { currDay: new Date().getDate(), currMonth: new Date().toLocaleString([], { month: 'long', }), currYear: new Date().getFullYear(), }; }, }; </script>
The current day of the month is displayed.
The current day of the month is displayed.

Get current year, month, day, week…

While you could get each component of the date using different functions, a much more flexible and easy way to do this is by formatting the date in the given format with a format specifier.

We can carry out this formatting with the format() function from the date-fns library.

In the following example, we use date-fns format() to get the multiple individual parts of the date.

App.vue
<template> <div>{{ dateString }}</div> </template> <script> import { format } from 'date-fns'; export default { data() { return { dateString: format( new Date(), "EEEE, 'the' do 'of' LLLL, yyyy" ), }; }, computed() { return {}; }, }; </script>
Different parts of the date are displayed using formatting.
Different parts of the date are displayed using formatting.

The format() function takes a pattern and returns a formatted date string in the format specified by the pattern. You can find a list of the patterns format() accepts here.

For our example, we use the following patterns:

  • EEEE: to get the full name of the day of the week.
  • do: to get the ordinal day of the month, i.e., 1st, 2nd, 3rd, etc.
  • LLLL: to get the full name of the month of the year.
  • yyyy: to get the full year.

We also use single quotes to escape strings (the and of) that are not patterns but should be included in the result of the formatting.

When Exactly is the useEffect Hook Called in React?

The useEffect hook is called in a component after the first render and every time the component updates. By the timer useEffect is called, the real DOM would have been updated to reflect any state changes in the component.

Let’s take a look at a quick example to practically observe this behavior:

JavaScript
import { useEffect, useState } from 'react'; export default function App() { const [count, setCount] = useState(0); useEffect(() => { document.title = `Button Clicks: ${count}`; }, [count]) const handleAdd = () => { setCount((count) => count + 1); } return ( <div> Count: {count} <br /> <button onClick={handleAdd}>Add</button> </div> ); }

The first time the component renders from page loading, useEffect is called and uses the document.title property to set the page title to a string whose value depends on a count state variable.

The page title is changed from useEffect being called after the component renders.
The page title is changed from useEffect being called after the component is rendered.

If you watch closely, you’ll see that the page title was initially “Coding Beauty React Tutorial”, before the component was added to the DOM and the page title was changed from the useEffect call.

useEffect will also be called when the state is changed:

The page title is changed from useEffect being called after the component updated.
The page title is changed from useEffect being called after the component is updated.

As you might know, useEffect accepts an optional dependency array as its second argument. This array contains the state variables, props, and functions that it should watch for changes.

In our example, the dependency array contains only the count state variable, so useEffect will only be called when the count state changes.

useEffect called twice in React 18?

React 18 introduced a new development-only check to Strict Mode. This new check automatically unmounts and remounts a component when it mounts for the first time, and restores the previous state on the second mount.

Note: The check was added because of a new feature that will be added to React in the future. Learn more about it here.

This means that the first render causes useEffect to actually be called two times, instead of just once.

Here’s an example that lets us observe this new behavior.

JavaScript
import { useEffect, useState } from 'react'; export default function App() { const [time, setTime] = useState(0); useEffect(() => { setInterval(() => { setTime((prevTime) => prevTime + 1); }, 1000); }, []); return ( <div> Seconds: {time} </div> ); }

It’s a basic time-counting app that implements the core logic that can be used to build timer and stopwatch apps.

We create an interval listener with setInterval() that increments a time state by 1 every second. The listener is in a useEffect that has an empty dependency array ([]), because we want it to be registered only when the component mounts.

But watch what happens when we check out the result on the web page:

The seconds go up by 2 every second.
The seconds go up by 2 every second.

The seconds are going up by 2 every second instead of 1! Because React 18’s new check causes the component to be mounted twice, an useEffect is called accordingly.

We can fix this issue by unregistering the interval listener in the useEffect‘s cleanup function.

JavaScript
useEffect(() => { const timer = setInterval(() => { setTime((prevTime) => prevTime); }); // 👇 Unregister interval listener return () => { clearInterval(timer); } }, [])

The cleanup function that the useEffect callback returns is called when the component is mounted. So when React 18 does the compulsory first unmounting, the first interval listener is unregistered with clearInterval(). When the second interval listener is registered on the second mount, it will be the only active listener, ensuring that the time state is incremented by the correct value of 1 every second.

The second go up by 1 every second - success.
The seconds go up by 1 every second – success.

Note that even if we didn’t have this issue of useEffect being called twice, we would still have to unregister the listener in the cleanup function, to prevent memory leaks after the component is removed from the DOM.

How to Easily Handle the onScroll Event in Vue

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

For example:

App.vue
<template> <div id="app"> Scroll top: <b>{{ scrollTop }}</b> <br /> <br /> <div id="box" @scroll="handleScroll" > <p v-for="i in 10" :key="i" > Content </p> </div> </div> </template> <script> export default { data() { return { scrollTop: 0, }; }, methods: { handleScroll(event) { this.scrollTop = event.currentTarget.scrollTop; }, }, }; </script> <style scoped> #box { border: 1px solid black; width: 400px; height: 200px; overflow: auto; } </style>
The text is update when the componet's onScroll event fires.
The text is updated when the component’s onScroll event fires.

We use the @ character to set a listener for an event on the component.

Vue
<div id="box" @scroll="handleScroll" > <!-- ... --> </div>

The @ character is a shorter alternative to v-on:

Vue
<div id="box" v-on:scroll="handleScroll" > <!-- ... --> </div>

The function (event handler) passed to the scroll event 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 scroll listener was attached to.

Apart from detecting scroll events, we can also scroll to the element in Vue.js.

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.

Handle onScroll event on window object

We can also handle the onScroll event on the global window object, to perform an action when the viewport is scrolled.

The addEventListener() method lets us do this:

JavaScript
<template> <div id="app"> Scroll top: <b>{{ scrollTop }}</b> <br /> <br /> <div id="label">Scroll top: {{ scrollTop }}</div> <div> <p v-for="i in 30" :key="i" > Content </p> </div> </div> </template> <script> export default { data() { return { scrollTop: 0, }; }, methods: { handleScroll() { this.scrollTop = window.scrollY; }, }, mounted() { window.addEventListener('scroll', this.handleScroll); }, beforeUnmount() { window.removeEventListener('scroll', this.handleScroll); }, }; </script> <style scoped> #label { position: fixed; padding: 10px 0; top: 0; background-color: white; border-bottom: 1px solid #c0c0c0; width: 100%; } </style>
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, e.g., 'click', 'keydown', 'scroll', etc.
  2. listener: the function called when the event fires.

It also has some optional parameters, which you can learn more about here.

We call addEventListener() in the mounted hook to register the listener once the component renders as the page loads. mounted is only called for a component when it has been added to the DOM, so the listener will not be registered multiple times.

We also called the removeEventListener() method to unregister the event listener and prevent a memory leak. We place the call in the beforeUnmount hook so that it happens just before the component is removed from the DOM.

How to Toggle a Boolean State in React

To toggle a boolean state in React:

  1. Use the useState hook create the boolean state (if you haven’t already).
  2. Pass a callback to the state updater function (setState).
  3. Return the negation of the boolean variable from the callback.

For example:

JavaScript
import { useState } from 'react'; export default function App() { const [visible, setVisible] = useState(false); const handleToggle = () => { setVisible((current) => !current); }; return ( <div> <button onClick={handleToggle}>Show name</button> {visible && <p>Coding Beauty</p>} </div> ); }
The text's visibility is toggled on button click
The text’s visibility is toggled on button click

We create the boolean state with the useState hook. useState returns an array of two values, the first is the value of the state, the second is a function that updates the state when it is called.

We pass a callback function to setVisible because the callback is always passed the latest visible state.

Tip: Always pass a function to setState when the new state is computed from the current state data.

In our case, the callback simply negates the boolean value and returns the result to negate the state.

The logical NOT (!) operator converts a truthy value to false and a falsy value to true.

JavaScript
console.log(!true); // false console.log(!false); // true console.log(!5); // false console.log(!undefined); // true

Note: In JavaScript there are only 6 falsy values: undefined, null, '' (empty string), NaN, 0, and false. Every other value is truthy and will result in false when negated.

Perform action on boolean state toggle

Sometimes you want to perform an action outside of re-rendering when the boolean state changes in the component, e.g., a network request. To carry out such an action, place the code in the useEffect hook and include the boolean state variable in useEffect‘s dependencies array.

JavaScript
import { useEffect, useState } from 'react'; import axios from 'axios'; export default function App() { const [visible, setVisible] = useState(false); const handleToggle = () => { setVisible((current) => !current); }; useEffect(() => { if (visible) { axios.post('https://example.com/stats/name/views').then(() => { console.log('Updated stats successfully.') }); } }, [visible]); return ( <div> <button onClick={handleToggle}>Show name</button> {visible && <p style={{ color: 'blue' }}>Coding Beauty</p>} </div> ); }

The code in the useEffect hook runs after the component mounts or updates from a change in the visible state. Here, the state controls the visibility of an element, so in the hook, we check if the element is visible, and if so, we make a network request to a server to update view stats associated with the element.

Perform action on boolean state change but skip first render

Depending on your scenario, you might want the action to run when the component updates from a state change, but not it when it first mounts.

We can do this by creating a ref flag variable having an initial value of false in the first render, and change its value to true for all subsequent renders.

JavaScript
import { useEffect, useRef, useState } from 'react'; import axios from 'axios'; export default function App() { const afterFirstRender = useRef(false); const [visible, setVisible] = useState(false); const handleToggle = () => { setVisible((current) => !current); }; useEffect(() => { if (!afterFirstRender.current) { afterFirstRender.current = true; return; } if (visible) { axios.post('https://example.com/stats/name/show').then(() => { console.log('Stats updated successfully') }); } }, [visible]); return ( <div> <button onClick={handleToggle}>Show name</button> {visible && <p style={{ color: 'blue' }}>Coding Beauty</p>} </div> ); }

useRef returns a mutable ref object that doesn’t change value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.

If the ref’s value is false, we prevent the action from happening in useEffect and change the value to true for the following renders. Otherwise, we execute the action.

How to Filter Duplicate Objects From an Array in JavaScript

1. Only keep first object in array with property value

To filter duplicate objects from an array by a property in JavaScript, use the filter() method to filter out elements that are not the first in the array having the property value.

For example:

JavaScript
const arr = [ { name: 'John', location: 'Los Angeles', }, { name: 'Kate', location: 'New York', }, { name: 'Mike', location: 'New York', }, ]; const unique = arr.filter( (obj, index) => arr.findIndex((item) => item.location === obj.location) === index ); /* [ { name: 'John', location: 'Los Angeles' }, { name: 'Kate', location: 'New York' } ] */ console.log(unique);

The Array filter() tests each element in an array against a condition specified by a callback function, and creates a new array filled with elements that pass the test. It doesn’t modify the original array.

JavaScript
const arr = [1, 2, 3, 4]; const filtered = arr.filter((num) => num > 2); console.log(filtered); // [ 3, 4 ]

The Array findIndex() method searches through elements in an array and returns the index of the first one that passes a test, specified by the callback function passed to it. We use it to find the first array element with the same property value as the object filter() is currently testing.

In our example, the filter() condition for the object is that its array index be the same as the result of findIndex(). If this condition is true, it will mean that the object is the first array element with the property value. If it’s false, it’ll mean that there’s already an array item with that property value, so the object is a duplicate and shouldn’t be included in the result.

JavaScript
const arr = [ { name: 'John', location: 'Los Angeles', }, { name: 'Kate', location: 'New York', }, { name: 'Mike', location: 'New York', }, ]; // true - first object with location of New York console.log(1 === arr.findIndex((obj) => obj.location === 'New York')); // false - will not be included in result console.log(2 === arr.findIndex((obj) => obj.location === 'New York'));

Filter duplicate objects from array by multiple properties

Depending on your scenario, you may want an object to be considered a duplicate only if it has two or more properties that have the same value – multiple property values that are the same.

For that case, we’ll use filter() and findIndex() as before, but we’ll add extra comparisons between filter()‘s object and findIndex()‘s object for all the properties.

For example:

JavaScript
const arr = [ { name: 'Kate', location: 'New York' }, { name: 'Mike', location: 'New York' }, { name: 'Kate', location: 'New York' } ]; const unique = arr.filter( (obj, index) => arr.findIndex( (item) => item.location === obj.location && item.name === obj.name ) === index ) /* [ { name: 'Kate', location: 'New York' }, { name: 'Mike', location: 'New York' } ] */ console.log(unique);

2. Exclude duplicates from unique array

Here’s another way to filter duplicate objects from an array in JavaScript:

  1. Create an empty unique array that will store the unique objects.
  2. Loop through the objects in the array.
  3. For each object, add it to the unique array if it isn’t a duplicate. Otherwise, ignore it.

For example:

JavaScript
const arr = [ { name: 'John', location: 'Los Angeles', }, { name: 'Kate', location: 'New York', }, { name: 'Mike', location: 'New York', }, ]; const unique = []; for (const item of arr) { const isDuplicate = unique.find((obj) => obj.location === item.location); if (!isDuplicate) { unique.push(item); } } /* [ { name: 'John', location: 'Los Angeles' }, { name: 'Kate', location: 'New York' } ] */ console.log(unique);

We use the for...of loop to iterate over the array and perform an action for each object.

For each object, we use the find() method to check if it already exists in the unique array. Array find() searches for the first object in an array that passes a specified test, similar to findIndex(), but it returns the object itself instead of its array index.

JavaScript
const nums = [2, 5, 8, 13, 19]; const doubleDigit = nums.find((num) => num > 9); console.log(doubleDigit); // 13

If it’s not in the unique array, we simply add it with the push() method.

This method is not a one-liner like the first one, but you may find it easier to understand. It seems like the natural way you would go about removing duplicate items from a list as a human.

Filter duplicate objects from array by multiple properties

Like in the previous method, if multiple properties are used to determine if an object is a duplicate, you can simply add more checks for the properties – this time in the find() method:

JavaScript
const arr = [ { name: 'Kate', location: 'New York', }, { name: 'Mike', location: 'New York', }, { name: 'Kate', location: 'New York', }, ]; const unique = []; for (const item of arr) { // 👇 "name" and "location" used for duplicate check const duplicate = unique.find( (obj) => obj.location === item.location && obj.name === item.name ); if (!duplicate) { unique.push(item); } } /* [ { name: 'Kate', location: 'New York' }, { name: 'Mike', location: 'New York' } ] */ console.log(unique);

How to Round a Number to 2 Decimal Places in JavaScript

To round a number to 2 decimal places in JavaScript, call the toFixed() method on the number, i.e., num.toFixed(2). toFixed() will round and format the number to 2 decimal places.

For example:

JavaScript
const num = 5.3281; const result = num.toFixed(2); console.log(result); // 5.33 const num2 = 3.1417 const result2 = num2.toFixed(2); console.log(result2); // 3.14

The toFixed() method takes a number F and returns a string representation of a number with F number of digits after the decimal points. F here is determined by the first argument passed to toFixed(), the fractionDigits argument.

JavaScript
const num = 5.3281; console.log(num.toFixed(0)); // 5 console.log(num.toFixed(1)); // 5.3 console.log(num.toFixed(2)); // 5.33 console.log(num.toFixed(3)); // 5.328 console.log(num.toFixed(4)); // 5.3281 console.log(num.toFixed(5)); // 5.32810

Parse result of toFixed() to number

Remember, toFixed() returns a string representation:

JavaScript
const num = 5.3281; const result = num.toFixed(2); console.log(result); // 5.33 console.log(typeof result); // string

But we can always convert the result to a number with the Number() constructor:

JavaScript
const num = 5.3281; const result = Number(num.toFixed(2)); console.log(result); // 5.33 console.log(typeof result); // number

If the string has trailing zeroes, they will be removed in the conversion:

JavaScript
const num = 9.999999; const strResult = num.toFixed(2); const result = Number(strResult); console.log(strResult); //10.00 console.log(result); // 10

The trailing zeros after the decimal point don’t change the value of a number, so 10.00 is the same as 10 or 10.00000000

JavaScript
console.log(10.00 === 10); // true console.log(10.00000000 == 10); // true

Round decimal string to 2 decimal places

Sometimes the input might be stored as a string. In this case, we’ll first need to convert the number to a float with the parseFloat() function before using toFixed() to round it to 2 decimal places.

For example:

JavaScript
const numStr = '17.23593'; // 👇 convert string to float with parseFloat() const num = parseFloat(numStr); const result = num.toFixed(2); // 17.24 console.log(result);

Not all decimal numbers can be represented precisely in binary, so there are some rounding errors in JavaScript’s floating-point number system. For example:

JavaScript
console.log(44.85 * 0.1); // 4.485 console.log(45.85 * 0.1); // 4.585 console.log(46.85 * 0.1); // 4.6850000000000005 (?)

In this example, 46.85 x 0.1 equals 4.6850000000000005 because 46.85 can’t be accurately represented in binary floating-point format.

JavaScript
console.log((1.415).toFixed(2)); // 1.42 console.log((1.215).toFixed(2)); // 1.22 console.log((1.015).toFixed(2)); // 1.01 (?)

Like in the first one, here 1.015 is rounded down to 2 decimal places as 1.01 instead of 1.02, because 1.015 also can’t be represented accurately in the binary number system.

One of the most popular examples of this flaw is the classic 0.1 + 0.2:

JavaScript
console.log(0.1 + 0.2 === 0.3); // false console.log(0.1 + 0.2); // 0.30000000000000004

You can find this and more of other interesting JavaScript quirks in our Crazy JS Book.

How to Remove a Class From All Elements in JavaScript

To remove a class from all HTML DOM elements with JavaScript:

  1. Get a list of all the elements in the DOM with document.querySelectorAll('*').
  2. Iterate over the list with forEach().
  3. For each element, call classList.remove(class) to remove the class from each element.

i.e.:

JavaScript
const allElements = document.querySelectorAll('*'); // const allChildElementsOfParentWithClass = document.querySelectorAll('.class *'); // const allChildElementsOfParentWithId = document.querySelectorAll('#id *'); // const allChildElementsOfParentWithTag = document.querySelectorAll('tag *'); allElements.forEach((element) => { element.classList.remove('big'); });

For example:

HTML
<p class="big bold text">Coding</p> <p class="big bold text">Beauty</p> <div class="container"> <p class="big bold text">Dev</p> <button class="big btn">Visit</button> </div> <br /> <button id="remove">Remove class</button>
CSS
.bold { font-weight: bold; } .big { font-size: 1.5em; } .text { font-family: Arial; } .btn { color: white; background-color: blue; }
JavaScript
const removeBtn = document.getElementById('remove'); removeBtn.addEventListener('click', () => { const elements = document.querySelectorAll('*'); elements.forEach((element) => { element.classList.remove('big'); }); });

This will be the HTML after the button is clicked:

HTML
<p class="bold text">Coding</p> <p class="bold text">Beauty</p> <div> <p class="bold text">Dev</p> <button class="btn">Visit</button> </div> <br /> <button id="remove">Remove class</button>
The classes are removed from the element when the button is clicked.
The classes are removed from the element when the button is clicked.

We use the document.querySelectorAll() method to select all DOM elements.

We iterate over the elements in the list object with the forEach() method. This forEach() method works similarly to Array forEach().

classList.remove() method

We use the classList.remove() method to remove a class from the elements. You can remove multiple classes by passing more arguments to remove().

JavaScript
const elements = document.querySelectorAll('*'); elements.forEach((element) => { element.classList.remove('big', 'bold'); });

If any of the classes passed to remove() doesn’t exist on the element, remove() will ignore it, instead of throwing an error.

Remove class from all children elements of element

The previous example works for removing a class from every single element in the DOM. What if you want to remove all elements that are children of a specific DOM element, for instance, just children of the .container element in our example?

To do this, just prefix the * with the element’s selector and separate them with a space. I mean:

JavaScript
// Remove class from all children elements of .container div const elements = document.querySelectorAll('.container *'); elements.forEach((element) => { element.classList.remove('big'); });

Add class to all elements

Just like the classList.remove() method removes one or more classes from an element, the classList.add() method adds one or more classes to an element. This means that we can use it in the forEach() method to remove a class from all DOM elements:

JavaScript
const elements = document.querySelectorAll('.canvas *'); elements.forEach((element) => { element.classList.add('clickable', 'stylable'); });

How to Get the Window’s Width on Resize in React

The get the width of the browser window on resize in React, add a resize event listener to the window object, then access the innerWidth property in the listener.

For example:

JavaScript
import { useState, useEffect } from 'react'; export default function App() { const [windowWidth, setWindowWidth] = useState(window.innerWidth); useEffect(() => { const handleWindowResize = () => { setWindowWidth(window.innerWidth); }; window.addEventListener('resize', handleWindowResize); return () => { window.removeEventListener('resize', handleWindowResize); }; }); return ( <div> <h2>Width: {windowWidth}</h2> </div> ); }
The text is updated with the width of the window when it is resized.

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

The resize event is fired whenever the width or height of the window/document view changes.

We use the useState React hook to create a state variable that will update whenever the width of the window changes.

The useState hook returns an array of two values. The 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 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.

JavaScript
useEffect(() => { const handleWindowResize = () => { setWindowWidth(window.innerWidth); }; window.addEventListener('resize', handleWindowResize); return () => { window.removeEventListener('resize', handleWindowResize); }; });

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

NoteuseEffect‘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.

Get window height on resize

We can do a similar thing to get the window’s height on resize, but we’ll use the window object’s innerHeight property instead in the resize event listener:

JavaScript
import { useState, useEffect } from 'react'; export default function App() { const [windowHeight, setWindowHeight] = useState(window.innerHeight); useEffect(() => { const handleWindowResize = () => { setWindowHeight(window.innerHeight); }; window.addEventListener('resize', handleWindowResize); return () => { window.removeEventListener('resize', handleWindowResize); }; }); return ( <div> <h2>Height: {windowHeight}</h2> </div> ); }
The text is updated with the height of the window when it is resized.

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